import { JoystickModule } from "../JoystickModule";
import { DispatcherManager } from "../utils/DispatcherManager";
import {GameState} from "../utils/GameState";
import {SceneControl} from "../Control/SceneControl";
import {PropManager} from "../PrefabControl/PropManager";
import {NpcScript} from "../Game/NpcScript";
import {TimerService} from "../Time/TimerService";
import GameCFG from "../CFG/GameCFG";
import {AudioControl} from "../Control/AudioControl";
import { WxApi } from "../WXSDK/Sdk";
import {RoleData} from "../Data/RoleData";
import {PanelResDic} from "../PrefabControl/PanelResDic";
import {AgencyUserMessage} from "../Agency/AgencyUserMessage";
import {AgencyTrial} from "../Agency/AgencyTrial";
import {AgencySkin} from "../Agency/AgencySkin";
import {SkinData} from "../Data/SkinData";
import { DisPatcherOn } from "../utils/DisPatcherOn";
import { RecordManager } from "../WXSDK/RecordManager";

export class GameStateControl implements TimerControl
{
    private static ins:GameStateControl;

    private _joystickModule:JoystickModule;

    /**
     * 0:未开始，1：游戏中，2：暂停中
     */
    nowGameState:number = 0;

    private _zhuanxiangbeishu:number = 0;
    constructor(){
        GameStateControl.ins = this;
    }

    public static get Instance():GameStateControl
    {
        if( GameStateControl.ins == null )
        {
            return new GameStateControl();
        }
        return GameStateControl.ins;
    }   

    private _huadongSpeedX:number = 0;
    private _huadongClimbSpeedX:number = 0;

    public endGamePlayerArr:Array<string> = [];

    public init( ):void
    {
        this._huadongSpeedX = Number(GameCFG.dict[4].value);
        this._huadongClimbSpeedX = Number(GameCFG.dict[5].value);
        if( GameCFG.dict[7] )
        {
            this._zhuanxiangbeishu = Number( GameCFG.dict[7].value );
        }
        else
        {
            this._zhuanxiangbeishu = 2;
        }
        
        this.initEvent();
    }

    private initEvent():void
    {
        DispatcherManager.addEventListener( GameState.lose,this,this.endGame);
        DispatcherManager.addEventListener( GameState.end,this,this.endGame );
        DispatcherManager.addEventListener( GameState.npcend,this,this.npcendGameHandler );
    }

    private npcendGameHandler( str:string ):void
    {
        this.endGamePlayerArr.push( str );
    }

    public setClickPanel( panel:fairygui.GLoader ):void
    {
        this._joystickModule = new JoystickModule(panel);
        this._joystickModule.setEventCallback( this,this.ondownfun,this.onmovefun,this.onupfun );
    }

    private _isneedShunyiX:boolean = false;
    private _nowTime:number = 0;
    private ondownfun():void
    {
        this._lastAngle = 0;
        this._nowTime = Laya.Browser.now()/1000;
    }
    private _lastAngle:number = 0;
    private onmovefun( offsetX:number ):void
    {
        if( this.nowGameState == 1 )
        {
            var disAngle:number = this._joystickModule.angle - this._lastAngle;
            this._lastAngle = this._joystickModule.angle;
            if( PropManager.iscarmanpc )
            {
                (PropManager.npcscriptDict["npc_0"] as NpcScript).Joy(offsetX > 0 ? this._huadongSpeedX:-this._huadongSpeedX,disAngle*this._zhuanxiangbeishu);
            }
            else
            {
                SceneControl.Instance.PlayerScript.Joy( offsetX > 0 ? this._huadongSpeedX:-this._huadongSpeedX,offsetX > 0 ? this._huadongClimbSpeedX:-this._huadongClimbSpeedX,disAngle*this._zhuanxiangbeishu );
            }
        }
    }

    private onupfun():void
    {
        if( PropManager.iscarmanpc )
        {
            (PropManager.npcscriptDict["npc_0"] as NpcScript).Joy(0,0);
        }
        else
        {
            if( this.nowGameState == 1 )
            {
                SceneControl.Instance.PlayerScript.Joy( 0,0,0 );
            }
        }
    }

    private _time:number = 0;
    public nowMingCi:number = 0;
    private _nums:number = 0;
    private _all:number = 0;
    public update( dt:number ):void
    {
        if( this.nowGameState == 1 )
        {
            this._time = 0;
            var npcdict:any = PropManager.npcscriptDict;
            this._nums = 0;
            this._all = 0;
            var s;
            var npcsp:NpcScript;
            for( s in npcdict )
            {
                npcsp = npcdict[s];
                if( npcsp.getAction() == 1 )
                {
                    if( PropManager.mainRole.transform.position.z < npcsp.getPostion().z )
                    {
                        this._nums++;
                    }
                    this._all ++;
                }
            }
            this.nowMingCi = this.endGamePlayerArr.length + (( this._all + 1 ) - this._nums);
            PropManager.txt_mingci.text = "第" + this.nowMingCi + "名";
        }
    }

    public startGame():void
    {
        var RoleData:RoleData = (PanelResDic.Instance.getSingleTon( AgencyUserMessage ) as AgencyUserMessage).RoleData;
        var agencyskin:AgencySkin = PanelResDic.Instance.getSingleTon( AgencySkin );
        var nohasskinArr:Array<SkinData> = agencyskin.GainNoHaveSkin();
        if( nohasskinArr.length == 0  )
        {
            this.entergame();
        }
        else
        {
            ( PanelResDic.Instance.getSingleTon( AgencyTrial ) as AgencyTrial ).openview(nohasskinArr);
        }
    }

    public entergame(jiasu?):void
    {
        RecordManager.Instance.RecordStart();
        this.nowMingCi = 0;
        this.endGamePlayerArr.length = 0;
        this.nowGameState = 1;
        TimerService.Instance.addUpdateTarget( this );
        this.update( 500 );
        if(jiasu){
            DispatcherManager.dispatchEvent( GameState.start,jiasu );
        }
        else{
            DispatcherManager.dispatchEvent( GameState.start );
        }
        AudioControl.Instance.playbgSound("bgm");
        WxApi.recordAldEvent("主界面点击开始游戏...");
    }

    public stopGame():void
    {
        this.nowGameState = 2;
        this.onupfun();
    }

    public endGame():void
    {
        if( PropManager.jiantouArr && PropManager.jiantouArr.length > 0 )
        {
            var arr:Array<Laya.MeshSprite3D> = PropManager.jiantouArr;
            for( var i:number =arr.length-1;i >=0;i--  )
            {
                arr[i].destroy();
                arr.splice( i,1 );
            }
        }
        PropManager.jiantouArr.length = 0;
        this.nowGameState = 0;
        TimerService.Instance.removeUpdateTarget( this );
        var npcdict:any = PropManager.npcscriptDict;
        if( npcdict )
        {
            for( var s in npcdict )
            {
                (npcdict[s] as NpcScript).stop();
            }
        }
        this.onupfun();
        AudioControl.Instance.stopbgSound();
    }
}