import 'dart:async';
import 'dart:io';

import 'package:flutter/services.dart';
import 'package:get/get_utils/src/platform/platform.dart';
import 'package:injectable/injectable.dart';
import 'package:keyboard/module/intro/intro_page.dart';
import 'package:keyboard/module/new_user/new_user_page.dart';
import 'package:lottie/lottie.dart';

import '../../base/base_controller.dart';
import '../../data/consts/constants.dart';
import '../../dialog/agreement_again_dialog.dart';
import '../../dialog/agreement_dialog.dart';
import '../../resource/assets.gen.dart';
import '../../sdk/umeng/umeng_helper.dart';
import '../../utils/privacy_compliance.dart';
import '../main/main_page.dart';

@injectable
class SplashController extends BaseController {
  final splashDelayedTime = 2;

  @override
  Future<void> onInit() async {
    super.onInit();
    await AssetLottie(Assets.anim.animIntroFirstData).load();
    await AssetLottie(Assets.anim.animIntroSecondData).load();
  }

  @override
  void onReady() {
    final isAgreePrivacy = PrivacyCompliance.isAgreePrivacyPolicy();
    if (isAgreePrivacy) {
      isAgreePrivacyNextStep();
    } else {
      AgreementDialog.show(
        cancelClick: () {
          AgreementAgainDialog.show(
            cancelClick: () {
              exitApp();
            },
            sureClick: () {
              _agreePrivacy();

            },
          );
        },
        sureClick: () {
          _agreePrivacy();

        },
      );
    }
  }

  void isAgreePrivacyNextStep() {
    _goMain(Duration(microseconds: 800));
  }

  void _goMain(Duration delayTime, {Map<String, dynamic>? arguments}) {
    Timer(delayTime, () {
      if (isFirstIntro()) {
        IntroPage.start();
      } else {
        MainPage.start(arguments: arguments);
      }
    });
  }

  void exitApp() {
    if (GetPlatform.isAndroid) {
      SystemNavigator.pop();
    }
    exit(0);
  }

  void _agreePrivacy() async {
    PrivacyCompliance.setPrivacyPolicy(true);
    if(Platform.isAndroid){
      await UmengHelper.setPolicyGrantResult(true);
    }
    else if(Platform.isIOS){
       UmengHelper.initCommon();
    }
    isAgreePrivacyNextStep();
  }
}
