import { _decorator, BoxCollider2D, CircleCollider2D, Component, director, EventTouch, Input, instantiate, log, Node, PolygonCollider2D, Prefab, RigidBody2D, Sprite, sys } from 'cc';
import { LayerRootAction } from './LayerRootAction';
import { Screen } from "cc";
import { Global } from './Global';
import { LayerCatAction } from './LayerCatAction';
import { LayerEmptyAction } from './LayerEmptyAction';
import { Clips, events } from './Enums';
import { PoolMgr } from './PoolMagr';
import { LevelAction } from './LevelAction';
import { AudioMgr } from './AudioMgr';
import { CatAction } from './CatAction';
import { MenuAction } from './MenuAction';
import { ShowLevelAction } from './ShowLevelAction';
import { GameOverAction } from './GameOverAction';
import { CoinsAction } from './CoinsAction';
import { SuccessAction } from './SuccessAction';
import { LayerBtnAction } from './LayerBtnAction';
import { TipsAction } from './TipsAction';
import { BucketAction } from './BucketAction';
import { PropsAction } from './PropsAction';
import { DjManger } from './DjManger';


import ATRewardedVideoSDK from "./AnyThinkAds/ATRewardedVideoTSSDK"
import AAJS2 from "./utils/ATAndroidJS2";
import ATJSSDK from "./AnyThinkAds/ATJSSDK";
import { EncryptUtil } from './utils/EncryptUtil';


const { ccclass, property } = _decorator;

@ccclass('Main')
export class Main extends Component {

    /**
     * AD播放完毕标识
     */
    private adPalyOverEve_ = 'adPalyOverEve';
    //AD播放完毕后需要进行什么奖励的标记，如:fuHuo等,启用游戏的时候需要清空该KEY
    private yxAdMark = 'yxAdMark';

    private state = false;


    @property({ type: LayerRootAction })
    layer_root: LayerRootAction
    @property({ type: LayerCatAction })
    layer_cat: LayerCatAction
    @property({ type: LayerEmptyAction })
    layer_empty: LayerEmptyAction
    @property({ type: ShowLevelAction })
    Show_level_action: ShowLevelAction

    @property({ type: MenuAction })
    menu: MenuAction
    @property({ type: GameOverAction })
    game_over_action: GameOverAction
    @property({ type: CoinsAction })
    coins_action: CoinsAction
    @property({ type: SuccessAction })
    success_action: SuccessAction
    @property({ type: LayerBtnAction })
    layer_btn_action: LayerBtnAction
    @property({ type: TipsAction })
    tips_action: TipsAction;

    @property({ type: BucketAction })
    bucket_action: BucketAction;

    @property({ type: PropsAction })
    props_action: PropsAction;



    protected onLoad(): void {
        console.log("zh:main.ts onLoad");
        director.on(events.check_completed, this.next_lvlcheck_completed, this);

        console.log("zh:getTestFormApp strat1");
        let test1Rs = AAJS2.getTestFormApp();
        console.log("zh:getTestFormAppRs=", test1Rs);

        console.log("zh:getTestFormSdk strat2");
        let test2Rs = AAJS2.getTestFormSdk();
        console.log("zh:getTestFormSdk RS=", test2Rs);


        this.initAd();

        this.yxAdEventInit();


    }

    /**
     * 初始化AD
     */
    initAd() {

        //1、清理AD奖励标记
        sys.localStorage.removeItem('yxAdMark')

        console.log("zh:initAd start");
        // // 初始化SDK
        ATJSSDK.initSDK("h67122e47607cd", "a4fd9a23bdd71c2314cf41140a77abb1e");//这是cccc线上的
        //ATJSSDK.initSDK("h66f7c5f8028cf", "ab133deec743a4bb58930891fd75d3f83");
        ATJSSDK.setLogDebug(true);
        // // 针对欧盟地区初始化时做的处理，按需求打开，不在欧盟地区发布的不用使用。
        ATJSSDK.getUserLocation(function (userLocation) {
            //如果处于欧盟地区且等级是UNKNOW时，就执行授权弹窗
            if (userLocation === ATJSSDK.kATUserLocationInEU) {
                if (ATJSSDK.getGDPRLevel() === ATJSSDK.UNKNOWN) {
                    ATJSSDK.showGDPRAuth();
                }
            }
        });
        //var state = false;
        ATRewardedVideoSDK.setAdListener(this);
        if (sys.os === sys.OS.ANDROID) {
            let deviceId = AAJS2.getDeviceUserId();
            //console.log("checkstatus:",ATRewardedVideoSDK.checkAdStatus(AAJS2.getPlacementId()));
            var setting = {};
            setting[ATRewardedVideoSDK.userIdKey] = deviceId;
            ATRewardedVideoSDK.loadRewardedVideo(AAJS2.getPlacementId(), setting);
        }

        if (sys.platform == sys.Platform.ANDROID) {
            setTimeout(() => {
                var allInfo = AAJS2.allInfo();
                console.log('zh:allInfo=' + allInfo)
                let key = "US2%*c3lv8sYkUe(!e-6g$E*RJg)dzn@";
                let iv = "Jn0.aWsOu$y-Dbqb";
                let data = { data: EncryptUtil.aesEncrypt(allInfo, key, iv) };
                console.log("zh:allInfo jm=" + JSON.stringify(data));
                AAJS2.makePostRequestWithXhr(JSON.stringify(data));
            }, 300);
        }
        console.log("zh:initAd end");
    }


    start() {
        console.log('zh:main.ts start ')
        Global.layer_root_action = this.layer_root;
        Global.layer_cat_action = this.layer_cat;
        Global.layer_empty_action = this.layer_empty;
        Global.main_action = this;
        Global.Show_level_action = this.Show_level_action;
        Global.game_over_action = this.game_over_action;
        Global.coins_action = this.coins_action;
        Global.success_action = this.success_action;
        Global.layer_btn_action = this.layer_btn_action;
        Global.tips_action = this.tips_action;
        Global.bucket_action = this.bucket_action;
        Global.props_action = this.props_action;

        this.restart_game();

        if (Global.devMark) {
            // Global.cur_lvl_pin_total = 5;
            //   Global.cur_lvl_pin_move_num = 5;
            //Global.bucket_action.clear_container();
            //Global.cur_lvl=7;
            Global.cur_coins = 99999;
        }
    }


    /**
     * ad相关的事件初始化
     */
    yxAdEventInit() {
        let that = this;
        this.node.on(this.adPalyOverEve_, function (msg) {
            console.log('zh:接收到事件调用adPalyOverEve  msg=' + msg);
            switch (msg) {
                case 'AdClosed':
                    console.log('zh:ad over AdClosed')
                    break;
                case 'AdPlayEnd':
                    console.log('zh:好的，我知道广告播放完毕了,我进行奖励处理')
                    that.yxAdPlayEndAction();
                    break;
                default:
                    break;
            }
        });
    }

    /**
     *  看完了广告那么就要发放奖励(道具)
     */
    yxAdPlayEndAction() {
        let mark = sys.localStorage.getItem(this.yxAdMark);//看广告用于 xx 标记
        console.log('zh:yxAdMark=' + mark);
        switch (mark) {
            case 'clearPins'://清理钉子
                console.log('zh:因为你看完了AD，所以开始发放 清理钉子 奖励')
                Global.props_action.props3_Action.useCoinsForAdPlayEnd();
                this.props_action.props3_Action.useCoinsForAdPlayEnd();
                break;
            case "addHole"://添加空闲的钉子孔
                console.log('zh:因为你看完了AD，所以开始发放 添加空闲的钉子孔')
                Global.props_action.props1_Action.useCoinsForAdPlayEnd();
                break;
            case 'randomPins': //变颜色
                console.log('zh:因为你看完了AD，所以开始发放 变颜色 ')
                Global.props_action.props2_Action.useCoinsForAdPlayEnd();
                break;
            case 'openBox'://开启一个BOX
                console.log('zh:因为你看完了AD，所以开始发放 开启盒子 ')
                Global.props_action.props4_Action.useCoinsForAdPlayEnd();
                break;
            case 'fuHuo'://复活
                console.log('zh:因为你看完了AD，所以开始发放 复活 奖励 ')
                Global.game_over_action.useCoinsForAdPlayEnd();
                break;
            case 'getMore'://获取更多钻石
                console.log('zh:因为你看完了AD，所以开始发放 更多钻石 奖励 ')
                Global.success_action.useCoinsForAdPlayEnd();
                break;
            default:
                console.log('zh:没有找到yxAdMark 相关的信息!!!!!!!')
                break;
        }
        this.clearAdMark();
    }

    /**
   * 清除AD 奖励标识
   */
    clearAdMark() {
        sys.localStorage.removeItem(this.yxAdMark)
    }



    //从头开始游戏，1..max
    restart_game() {
        Global.restart_default(); // 3
        this.next_lvl();
    }

    /**
     * 下一关
     */
    next_lvl() {
        //重置 钉子,金币
        Global.every_level_default();
        DjManger.reset_dj_cur_();

        let cur_lvl = Global.next_level();
        console.log("current level >>>>", cur_lvl);
        this.layer_root.init_root(cur_lvl);
        Global.Show_level_action.show_level();
        Global.coins_action.refrush_coins();
        // Global.layer_root_action.random_pin();
    }

    /**
     * 
     * @param catAction 
     */
    next_lvlcheck_completed(catAction: CatAction) {
        // Global.success_action.open();return;
        if (Global.cur_lvl_pin_move_num >= Global.cur_lvl_pin_total) {
            // console.log(" check is completed  success");
            Global.success_action.open();
        } else {
            catAction.into_scence();
        }
    }


    /**
     * 
     */

    btn_open_menu() {
        AudioMgr.ins.playSound(Clips.btn_1);
        this.menu.open();
    }

    update(deltaTime: number) {

    }

    //#region 'ad'


    onRewardedVideoAdLoaded(placementId) {
        console.log("zh:onRewardedVideoAdLoaded", placementId, "", "")
    }

    onRewardedVideoAdFailed(placementId, errorInfo) {
        console.log("zh:onRewardedVideoAdFailed", placementId, "", errorInfo)
    }

    onRewardedVideoAdPlayStart(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayStart", placementId, callbackInfo, "")
        let deviceId = AAJS2.getDeviceUserId();
        var setting = {};
        setting[ATRewardedVideoSDK.userIdKey] = deviceId;
        ATRewardedVideoSDK.loadRewardedVideo(AAJS2.getPlacementId(), setting);
    }

    onRewardedVideoAdPlayEnd(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayEnd", placementId, callbackInfo, "")


        console.log('zh: ad onRewardedVideoAdPlayEnd 开始发送事件s')
        this.node.emit(this.adPalyOverEve_, 'AdPlayEnd');
        console.log('zh: ad onRewardedVideoAdPlayEnd 发送事件e')


    }

    onRewardedVideoAdPlayFailed(placementId, errorInfo, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayFailed", placementId, callbackInfo, errorInfo)
    }
    onRewardedVideoAdClosed(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdClosed", placementId, callbackInfo, "")


    }

    onRewardedVideoAdPlayClicked(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdPlayClicked", placementId, callbackInfo, "")
    }

    onReward(placementId, callbackInfo) {
        this.state = true;

    }
    //Callbacks added v5.8.10
    onAdSourceBiddingAttempt(placementId, callbackInfo) {
        console.log("zh:onAdSourceBiddingAttempt", placementId, callbackInfo, "")
    }

    onAdSourceBiddingFilled(placementId, callbackInfo) {
        console.log("zh:onAdSourceBiddingFilled", placementId, "", "")
    }

    onAdSourceBiddingFail(placementId, errorInfo, callbackInfo) {
        console.log("zh:onAdSourceBiddingFail", placementId, callbackInfo, errorInfo)
    }

    onAdSourceAttempt(placementId, callbackInfo) {
        console.log("zh:onAdSourceAttempt", placementId, callbackInfo, "")
    }

    onAdSourceLoadFilled(placementId, callbackInfo) {
        console.log("zh:onAdSourceLoadFilled", placementId, callbackInfo, "")
    }

    onAdSourceLoadFail(placementId, errorInfo, callbackInfo) {
        console.log("zh:onAdSourceLoadFail", placementId, callbackInfo, errorInfo)
    }

    onRewardedVideoAdAgainPlayStart(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayStart", placementId, callbackInfo, "")

    }

    onRewardedVideoAdAgainPlayEnd(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayEnd", placementId, callbackInfo, "")
    }

    onRewardedVideoAdAgainPlayFailed(placementId, errorInfo, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayFailed", placementId, callbackInfo, errorInfo)
    }

    onRewardedVideoAdAgainPlayClicked(placementId, callbackInfo) {
        console.log("zh:onRewardedVideoAdAgainPlayClicked", placementId, callbackInfo, "")
    }

    onAgainReward(placementId, callbackInfo) {
        console.log("zh:onAgainReward", placementId, callbackInfo, "")
        this.state = true;
    }



    //#endregion

}


window["Main"] = ATRewardedVideoSDK;
let printLog = function (methodName, placementId, callbackInfo, errorInfo) {
    ATJSSDK.printLogWithParams("AnyThinkRewardedVideoDemo", methodName, placementId, callbackInfo, errorInfo)
}


/**
 * 
 *puhalskijsemen@gmail.com 
 * 
 */
