import { bundleManager,abilityAccessCtrl, AbilityConstant, ConfigurationConstant,
  Permissions,
  UIAbility, Want,
  common } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import { HMRouterMgr } from '@hadss/hmrouter';
import {  } from '@kit.MDMKit';
import { AppCache } from '../app/AppCache';
import { UserCache } from '../app/UserCache';
import { FileUtils } from '../util/FileUtils';
import { DialogHelper } from '@pura/harmony-dialog';
import { ToastUtils } from '../util/ToasUtils';
import { UnauthorizedPermissionDialog } from '../ui/dialog/UnauthorizedPermissionDialog';
import { AppUtil } from '@pura/harmony-utils';

const DOMAIN = 0x0000;

export default class EntryAbility extends UIAbility {

  /**
   * TODO   {
   //        "name": "ohos.permission.GET_INSTALLED_BUNDLE_LIST",
   //        "reason":"$string:read_app_list_reason",
   //        "usedScene":{
   //          "abilities":[
   //            ".EntryAbility"
   //          ],
   //          "when":"inuse"
   //        }
   //      },
   */

  /**
   * @param want
   * @param launchParam
   */
  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    this.context.getApplicationContext().setColorMode(ConfigurationConstant.ColorMode.COLOR_MODE_NOT_SET);
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onCreate');
    HMRouterMgr.init({
      context: this.context
    })
    AppUtil.init(this.context)
    UserCache.getUserCache()
    this.applyForPermission()
    FileUtils.init(this.context)
    //初始化数据库
    // DBUtils.getInstance().HOInit(this.context)
    // 在Ability中监听事件
    this.context.eventHub.on('ui_event', (data:Array<Permissions>) => {
      // console.log('Received UI event:', data);
      if (data!=null) {
        this.requestPermissionsFromUser(data)
      }
    });

    //简单初始化（1.0.8版本及以后）
    //必须在UIAbility的onCreate方法里初始化context。
    DialogHelper.setDefaultConfig((config) => {
      config.uiAbilityContext = this.context;
    })
  }

  onDestroy(): void {
    this.context.eventHub.off("ui_event")
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageCreate');
    windowStage.getMainWindow().then((window=>{
      window.setWindowLayoutFullScreen(true)
    }))
    windowStage.loadContent('ui/pages/Index', (err) => {
      if (err.code) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      hilog.info(DOMAIN, 'testTag', 'Succeeded in loading the content.');
    });
    // set main window full screen
    // this.setAppFullScreen(windowStage.getMainWindowSync());
  }

  onWindowStageDestroy(): void {
    // Main window is destroyed, release UI related resources
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onWindowStageDestroy');
  }

  onForeground(): void {
    // Ability has brought to foreground
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onForeground');
  }

  onBackground(): void {
    // Ability has back to background
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onBackground');
  }


  //申请权限
  applyForPermission() {
    let  permissions = new Array<Permissions>();
    permissions.push('ohos.permission.CAMERA')
    permissions.push('ohos.permission.LOCATION')
    permissions.push('ohos.permission.APPROXIMATELY_LOCATION')
    // permissions.push('ohos.permission.GET_INSTALLED_BUNDLE_LIST')
    this.checkPermissionGrant(permissions)
  }

  checkPermissionGrant(permissionArray: Array<Permissions>) {
    let uiContext :common.UIAbilityContext  = this.context as common.UIAbilityContext;
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
    // 获取应用程序的accessTokenID
    let bundleInfo = bundleManager.getBundleInfoForSelfSync(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION)
    let appInfo: bundleManager.ApplicationInfo = bundleInfo.appInfo
    let tokenId: number = appInfo.accessTokenId
    let wsqPermissionArray = new Array<Permissions>()
    for (let i = 0; i < permissionArray.length; i++) {
      let grantStatus = atManager.checkAccessTokenSync(tokenId, permissionArray[i])
      if (grantStatus == abilityAccessCtrl.GrantStatus.PERMISSION_DENIED) {
        wsqPermissionArray.push(permissionArray[i])
      }
    }
    if (wsqPermissionArray.length>0) {
      //有未申请的权限
      this.requestPermissionsFromUser(wsqPermissionArray)
    }else {
      //授权成功
      this.sendPermissionSuccess(uiContext)
    }
  }

  /**
   *AUTHOR:AbnerMing
   *INTRODUCE:向用户获取权限授权
   */
  requestPermissionsFromUser(permissions: Array<Permissions>) {
    let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager()
    let uiContext :common.UIAbilityContext  = this.context as common.UIAbilityContext;
    atManager.requestPermissionsFromUser(uiContext, permissions)
      .then((data) => {
        let grantStatus: Array<number> = data.authResults;
        let length: number = grantStatus.length;
        let notPermissions: Array<Permissions> =new Array<Permissions>();
        for (let i = 0; i < length; i++) {
          if (grantStatus[i] === 0) {
            // 用户授权，可以继续访问目标操作
            console.log("===用户授权")
          } else {
            // 用户拒绝授权，提示用户必须授权才能访问当前页面的功能，并引导用户到系统设置中打开相应的权限
           notPermissions.push(permissions[i])
          }
        }
        if (notPermissions.length > 0) {
          //授权失败
          this.applyPermissionAgain(uiContext,atManager, notPermissions)
        }else {
          //授权成功
          this.sendPermissionSuccess(uiContext)
        }
        console.log("===权限授权成功")
      })
      .catch((err:Error) => {
        console.error("===权限授权失败")
      })
  }

  /**
   * 重新申请授权
   * @param uiContext
   * @param atManager
   * @param notPermissions
   */
  applyPermissionAgain(uiContext :common.UIAbilityContext,atManager: abilityAccessCtrl.AtManager,notPermissions: Array<Permissions>){
    ToastUtils.toastCenter("您拒绝了权限，请到设置里打开！")
    atManager.requestPermissionOnSetting(uiContext,notPermissions)
      .then((data) => {
        let  notAuthorizationCount = 0
        data.forEach((item) => {
          if (item == -1) {
            notAuthorizationCount++
          }
        })
        if (notAuthorizationCount == 0) {
          //授权成功
          this.sendPermissionSuccess(uiContext)
        }else {
          //授权失败
          this.sendPermissionFailed(uiContext)
        }
      })
      .catch((err:Error) => {
        //授权失败
        this.sendPermissionFailed(uiContext)
        console.error("===权限授权失败")
      })

    // HMRouterMgr.replace({navigationId:'startNavigation',pageUrl:"MainPage"})
    return
  }

  sendPermissionFailed(uiContext: common.UIAbilityContext){
    setTimeout(()=>{
      let dat  = "NotPermissions"
      uiContext.eventHub.emit('NotPermissions',dat);
    },1000)
  }

  sendPermissionSuccess(uiContext: common.UIAbilityContext){
    setTimeout(()=>{
      let dat  = "PermissionsSuccess"
      uiContext.eventHub.emit('PermissionsSuccess',dat);
    },1000)
  }




}