import ViewTop from "../main/ViewTop";
import CHttpEvent from "./CHttpEvent";
import CUtil from "./CUtil";

/**
 * 网络状态
 */
export enum HttpStateType{
    SUCCESS,
    TIME_OUT,
    ERROR,
}
/**
 * 服务器反馈消息
 */
export interface ReveData{
    retCode:number,
    message:string,
    data:any,
}


/**
 * http post
 */
export default class CHttp {
    private url:string = null;
    public id:string;
    public userId:number;
    public token:string = null;
    /**
     * 网络消息监听
     */
    public event:Array<CHttpEvent> = [];

    constructor(url) {
        this.url = url;
    }
    /**
     * 添加事件到头部
     * @param httpEvent 
     */
    public unshiftEvent(httpEvent:CHttpEvent){
        this.event.unshift(httpEvent);
    }
    public pushEvent(httpEvent:CHttpEvent){
        this.event.push(httpEvent);
        // cc.log('添加监听:')
        // for (let i = 0; i < this.event.length; i++) {
        //     const element = this.event[i];
        //     cc.log(element);
        // }
        // cc.log('----------end')
    }
    public popEvent(httpEvent:CHttpEvent){
        for (let i = 0; i < this.event.length; i++) {
            const element = this.event[i];
            if(element == httpEvent){
                this.event.splice(i,1);
                return
            }
        }
        // this.event.pop();
        // for (let i = 0; i < this.event.length; i++) {
        //     const element = this.event[i];
        //     cc.log(element);
        // }
        // cc.log('----------end')
    }
     /**
     * sendjson
     */
    public sendForm(action,msg,callback:(state:Number,reve?:ReveData)=>void) {
        if(this.id){
            msg.I = this.id;
        }
        if(this.userId){
            msg.userId = this.userId;
        }
        if(this.token){
            CUtil.makeSign(msg,this.token);
        }
        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.open('post',this.url+action,true);
        // xhr.setRequestHeader("Content-Type","text/plain");
        xhr.setRequestHeader("Content-Type","application/json");

        xhr.onerror = function(eventname){
            callback(HttpStateType.ERROR);
        };
        xhr.ontimeout = function(eventname){
            callback(HttpStateType.TIME_OUT);
        }
        let myself = this;
        xhr.onreadystatechange = function () {
            // cc.log('readyState = '+xhr.readyState);
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                if(CC_DEBUG){
                    cc.log('reve:'+xhr.responseText);
                }
                let jsonObj = JSON.parse(xhr.responseText)
                if(jsonObj.retCode == 0){
                    for (let i = 0; i < myself.event.length; i++) {
                        const element = myself.event[i];
                        element.httpEvent(jsonObj);
                    }
                }else if(jsonObj.retCode == 500106){
                    myself.initViewTop()
                }
                callback(HttpStateType.SUCCESS,jsonObj);
            }
        };
        if(CC_DEBUG){
            cc.log('send',JSON.stringify(msg));
        }
        xhr.send(JSON.stringify(msg));
    }
    /**
     * sendjson
     */
    public sendJson(action,msg,callback:(state:Number,reve?:ReveData)=>void) {
        if(this.id){
            msg.I = this.id;
        }
        if(this.userId){
            msg.userId = this.userId;
        }
        if(this.token){
            CUtil.makeSign(msg,this.token);
        }
        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.open('post',this.url+action,true);
        xhr.setRequestHeader("Content-Type","text/plain");
        // xhr.setRequestHeader("Content-Type","application/json");

        xhr.onerror = function(eventname){
            callback(HttpStateType.ERROR);
        };
        xhr.ontimeout = function(eventname){
            callback(HttpStateType.TIME_OUT);
        }
        let myself = this;
        xhr.onreadystatechange = function () {
            // cc.log('readyState = '+xhr.readyState);
            if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status < 300)) {
                if(CC_DEBUG){
                    cc.log('reve:'+xhr.responseText);
                }
                let jsonObj = JSON.parse(xhr.responseText)
                if(jsonObj.retCode == 0){
                    for (let i = 0; i < myself.event.length; i++) {
                        const element = myself.event[i];
                        element.httpEvent(jsonObj);
                    }
                }else if(jsonObj.retCode == 500106){
                    myself.initViewTop()
                }
                callback(HttpStateType.SUCCESS,jsonObj);
            }
        };
        if(CC_DEBUG){
            cc.log('send:'+action,JSON.stringify(msg));
        }
        xhr.send(JSON.stringify(msg));
    }


    private initViewTop(){
        cc.resources.load('prefab/common/common_hint', cc.Prefab, (err, prefab: cc.Prefab) => {
            if (err) {
                cc.error(err);
            } else {
                //加载结束
                let node: cc.Node = cc.instantiate(prefab);
                let viewTop = node.getComponent(ViewTop);
                viewTop.show()
            }
        });
    }


}
