import { AbilityConstant, bundleManager, ConfigurationConstant, UIAbility, Want } from '@kit.AbilityKit';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { window } from '@kit.ArkUI';
import {
  AppStorageKeyCollect,
  AppStorageKeyFishCollect,
  jHStartAd,
  permissionController,
  YTAvoid,
  YTBreakPoint,
  YTLog,
  YTUserRequest
} from 'basic';
import { preferences } from '@kit.ArkData';
import { identifier } from '@kit.AdsKit';
import { BusinessError } from '@kit.BasicServicesKit';

const DOMAIN = 0x0000;

export default class EntryAbility extends UIAbility {
  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');
  }

  onDestroy(): void {
    hilog.info(DOMAIN, 'testTag', '%{public}s', 'Ability onDestroy');
  }

  onWindowStageCreate(windowStage: window.WindowStage): void {

    windowStage.loadContent('/pages/Index'.slice(1), (err) => {
      if (err.code) {
        hilog.error(DOMAIN, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err));
        return;
      }
      YTLog.init({
        tag: "YTLog",
        domain: 0x0000,
        close: false,
        isHilog: true,
        showLogLocation: true,
        logSize: 800
      })

      PersistentStorage.persistProp<string>(AppStorageKeyCollect.TOKEN, '')

      //敲木鱼的文字动画
      PersistentStorage.persistProp<string>(AppStorageKeyFishCollect.FISHTEXT, '')
      PersistentStorage.persistProp<string[]>(AppStorageKeyFishCollect.TEXTARR, [])


      if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
        YTUserRequest.refreshUserInfo()
      }
      // IBestInit(windowStage, this.context)
      bundleManager.getBundleInfoForSelf(bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO)
        .then(res => {
          YTLog.info(`signatureInfo:` + JSON.stringify(res.signatureInfo))
        })
        .catch((err: Error) => {
          YTLog.error(err)
        })
      permissionController.init(this.context)
        .then(() => {
          permissionController.askPermission(["ohos.permission.APP_TRACKING_CONSENT"], (res, err) => {
            if (err) {
              YTLog.error(err)
            } else {
              if (res?.authResults[0] === 0) {
                YTLog.info('succeeded in requesting permission');
                identifier.getOAID((err: BusinessError, data: string) => {
                  if (err.code) {
                    YTLog.error(`get oaid failed, error: ${err.code} ${err.message}`);
                  } else {
                    const oaid: string = data;
                    jHStartAd.init(this.context, oaid)
                    AppStorage.setOrCreate('OAID', oaid)
                    YTLog.info(`succeeded in getting oaid by callback , oaid: ${oaid}`);
                  }
                });
              } else {
                YTLog.error('user rejected');
              }
            }
          })
        })
      // IBestSetGlobalConfig({
      //   unit: "vp",
      //   fontUnit: "vp"
      // })
      const windowClass = windowStage.getMainWindowSync()
      windowClass.setWindowLayoutFullScreen(true)
      const top = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM).topRect.height
      const bottom = windowClass.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR).bottomRect.height
      YTAvoid.setAvoid({
        top, bottom
      })
      windowClass.on('avoidAreaChange', avoidOption => {
        if (avoidOption.type == window.AvoidAreaType.TYPE_SYSTEM) {
          YTAvoid.setAvoid({
            top: avoidOption.area.topRect.height
          })
        }
        if (avoidOption.type == window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR) {
          YTAvoid.setAvoid({
            bottom: avoidOption.area.bottomRect.height
          })
        }
      })
      const windowWidth = windowClass.getWindowProperties().windowRect.width
      YTBreakPoint.setBreakPoint(windowWidth)
      windowClass.on('windowSizeChange', size => {
        YTBreakPoint.setBreakPoint(size.width)
      })
      //创建首选项 category
      let preference: preferences.Preferences | null = null
      preference = preferences.getPreferencesSync(getContext(), {
        name: 'category'
      })
      AppStorage.setOrCreate<preferences.Preferences>('category', preference)
    });

  }

  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');
  }
}