import DataModelManager from '../framework/DataModelManager';
import Define from './Define'
var Int64BE = require("int64-buffer").Int64BE;
var Uint64BE = require("int64-buffer").Uint64BE;
var Int64LE = require("int64-buffer").Int64LE;
var UInt64LE = require("int64-buffer").UInt64LE;


let Common = {
    'appid':'wxbf82ebb4482641b9',
    'appsecret':'184b026f981eb4d3c41f1c7a7607bc82',
    'androidappid':'wx68f7188d6939904f',
    'androidappsecret':'e4b7999d0db89df4d5caf5af57f048ef',
    'wxWindowWidth':1334,
    'wxwindowHeight':750,
    'littleEndian':(function() {
        var buffer = new ArrayBuffer(2);
        new DataView(buffer).setInt16(0, 256, true);
        return new Int16Array(buffer)[0] === 256;
      })(),
    'Trim':function(str,is_global)
    {
     var result;
     result = str.replace(/(^\s+)|(\s+$)/g,"");
     if(is_global.toLowerCase()=="g")
     {
      result = result.replace(/\s/g,"");
      }
     return result;
    }, 

    'sendGetGameConfig': function(url, callBack) {
        cc.log('Common sendGetGameConfig url:' + url);
        var request = cc.loader.getXMLHttpRequest();
        // request.responseType = 'arraybuffer';
        request.timeout = 120000; // 超时时间，单位是毫秒

        request.open("GET", url, true);
        request.ontimeout = function (e) {
            // XMLHttpRequest 超时。在此做某事。
            cc.log('sendGetGameConfig:ontimeout url: ' + url );
            callBack('timeOut', null);
           
          };
        request.onreadystatechange = function () {
            if (request.readyState == 4) {
                if (request.status >= 200 && request.status < 400) {
                    if (request.response && callBack) {
                        var uint8Array = new Uint8Array(request.response); 
                        var str = Common.Uint8ArrayToString(uint8Array)
                        callBack(null, request.response);
                    }
                } else {
                    callBack(request.status, '');
                }
            }
        };
        request.send();
    },

	'createImage':function(sprite,url){

        console.log("createImage: url:" + url );
		let self = this;
        let image = new Image();
		image.onload = function ()
		{
			let texture = new cc.Texture2D();
			texture.initWithElement(image);
			texture.handleLoadedTexture();
			sprite.spriteFrame = new cc.SpriteFrame(texture);
			console.log('createImage onload' );		
		};
        image.src = url;
    },
    
    'cardValue2SpStr':function(cardData)
    {
        var index = 0;
        if (0 != cardData) {
            var nColor = Math.floor(cardData / 16);
            var nValue = (cardData % 16);
            cc.log('cardData:' + cardData + '   nColor:' + nColor + '   nValue:' + nValue);
            
            if (nColor == 4) {
                index = (Math.floor(cardData / 16) - 1) * 13 + (cardData % 16) ;
            } else {
                index = Math.floor(cardData / 16) * 13 + (cardData % 16) ;
            }
        } else {
            //使用背面纹理区域
            index = 55;
        }

        return index
    },

    'RankType':
    {
        CityRank:0,
        ProvinceRank:1,
        CountryRank:2,
    },
    'TCPInfoSize':4,
    'DK_MAPPED':0x1,
    'ReConnect':
    {
        RECONNECT_INTERVAL:5,
        RECONNECT_TIME : 10,
    },

    'SceneType':
    {
        Lobby:1,
        Battle:2,
    },
    'MatchType':
    {
        Random:0,//随机匹配
        WeekOne:1,//智力周赛单人
        WeekTwo:2,//智力周赛双人
        FriendPK:3,//好友PK
    },

    'HonorType':
    {
        WithoutHonor:0, //没有荣誉
        JuniorHonor:1, //初级荣誉
        MiddleHonor:2, //中级荣誉
        AdvancedHonor:3, //进阶荣誉
        HighHonor:4, //高级荣誉
    },
    'Honor':
    {
        WithoutHonor:'', //没有荣誉
        JuniorHonor:'聪慧青铜', //初级荣誉
        MiddleHonor:'博学白银', //中级荣誉
        AdvancedHonor:'万卷宗师', //进阶荣誉
        HighHonor:'最强大脑', //高级荣誉
    },

    'GameState' :
    {
        SocketConnecting: 1,  // socket  connect  
        Matching: 2,  //  Matching   
        Gaming: 3,  //    Gaming 
        Result: 4,  //    Result  
    },
    'SocketState' : 
    {
        OK : 0,//可用
        Connecting : 1,//正在连接
        Closing : 2,//连接正在关闭
        Closed : 3,//关闭或出错
        ReConnecting:4,//重连中
        ConnectFail:5,//重连失败
        DisConnect:6,//断开连接
        Error:7,//错误
                   
    },
    'BGMState' :
    {
        NONE: 0,
        MAINMENU: 1,
        NORMAL: 2,
        NORMAL1: 3,
        EXCITING: 4,
    },

    'BGMUrl': {
        MAINMENU: Define.Prefix +'sounds/BGM/BG_Welcome',
        NORMAL: Define.Prefix +'sounds/BGM/BG_Normal',
        NORMAL1: Define.Prefix +'sounds/BGM/BG_Normal1',
        EXCITING: Define.Prefix +'sounds/BGM/BG_Exciting',
    },

    'EffectUrl' :
    {
        ClickButton : Define.Prefix +'sounds/SFX/2',
        ClickButtonFail : Define.Prefix +'sounds/SFX/3',
        DecreaseStrength : Define.Prefix +'sounds/SFX/4',
        Success : Define.Prefix +'sounds/SFX/7',
        Error : Define.Prefix +'sounds/SFX/8',
        ReadyGo : Define.Prefix +'sounds/SFX/9-1',
        CountDown : Define.Prefix + 'sounds/SFX/10',
        CountDownDeadTime : Define.Prefix +'sounds/SFX/11',
        Right_1 : Define.Prefix +'sounds/SFX/12-1',
        Right_2 :Define.Prefix + 'sounds/SFX/Y-1',
        Double : Define.Prefix +'sounds/SFX/12-2',
        Wrong : Define.Prefix +'sounds/SFX/13',
        DoubleKill_1 :Define.Prefix + 'sounds/SFX/14-1',
        DoubleKill_2 : Define.Prefix +'sounds/SFX/Y-2',
        TripleKill_1 : Define.Prefix +'sounds/SFX/14-2',
        TripleKill_2 : Define.Prefix +'sounds/SFX/Y-3',
        QuataryKill_1 :Define.Prefix + 'sounds/SFX/14-3',
        QuataryKill_2 : Define.Prefix +'sounds/SFX/Y-4',
        WrongAgain_1 : Define.Prefix +'sounds/SFX/15',
        WrongAgain_2 :Define.Prefix + 'sounds/SFX/N-2',
        IncreaseScore : Define.Prefix +'sounds/SFX/18',
        DoubleScore :Define.Prefix + 'sounds/SFX/20',
        Win : Define.Prefix +'sounds/SFX/21-1',
        Tie : Define.Prefix +'sounds/SFX/21-2',
        Lose :Define.Prefix + 'sounds/SFX/21-3',
        ResultScore : Define.Prefix +'sounds/SFX/22',
        PopWindow : Define.Prefix +'sounds/SFX/23',
        Honor : Define.Prefix +'sounds/SFX/25',
        Round : Define.Prefix +'sounds/SFX/28',
        EnemyRight :Define.Prefix + 'sounds/SFX/29',
        EnemyWrong : Define.Prefix +'sounds/SFX/30',
        EnemyIncreaseScore :Define.Prefix + 'sounds/SFX/31',
        TimeOut : Define.Prefix +'sounds/SFX/32',
        Result : Define.Prefix +'sounds/SFX/33',
        

    },
    'AddressCheck':function(province,city)
    {
        if(province== undefined || city == undefined)
        {
            return '来自:未知';
        }
        if(province.length<=0&&city.length<=0)
        {
            return '来自:未知';
        }

        return '来自:' + province + city;

    },
    'ClampLength':function(tstr)
    {
       
        if(tstr==null)
        {
            return 0;
        }
        var len = 0;
        var pattern = new RegExp("[\u4E00-\u9FA5]");
        var pattern2 = new RegExp("[A-Za-z0-9]+");
        var pattern2Len = 0.5;
        for (var i = 0; i < tstr.length; ++i)
        {
            if (pattern.test(tstr[i]))
            {
               len += 1;
               
            }
            else
            {
                
                len += 0.5;
               
            }
        }

        return len;

    },

    'ClampName':function(name)
    {
        // var pattern = new RegExp("[\u4E00-\u9FA5]");
        // var str = '中文字符'
        // if (pattern.test(str))
        // {
        //     alert('chinese');
        // }
        // var pattern2 = new RegExp("[A-Za-z]+");
        // var str2 = 'abcdefg';
        // if (pattern2.test(str2))
        // {
        //     alert('english')
        // }
        // var pattern3 = new RegExp("[0-9]+");
        // var str3 = 'abcdefg';
        // if (pattern3.test(str2))
        // {
        //     alert('number')
        // }
        // var len = name.length;
        // if (len > 5)
        // {
        //     return name.slice(0, 4) + '...';
        // }
        if (name.length <= 5)
        {
            return name;
        }

        var len = 0;
        var str = '';
        var totalLen = 5;
        var post = '...';
        var pattern = new RegExp("[\u4E00-\u9FA5]");
        var patternLen = 1;
        var pattern2 = new RegExp("[A-Za-z0-9]+");
        var pattern2Len = 0.5;
        for (var i = 0; i < name.length; ++i)
        {
            if (pattern.test(name[i]))
            {
                if (len + 1 <= totalLen - 1.5)
                {
                    str += name[i];
                    len += 1;
                }
                else
                {
                    break;
                }
            }
            else if (pattern2.test(name[i]))
            {
                if (len + 0.5 <= totalLen - 1.5)
                {
                    str += name[i];
                    len += 0.5;
                }
                else
                {
                    break;
                }
            }
        }
        return str+post;
    },

    'AdjustFit':function(node)
    {

        if(node==null)
        {
            return 0;
        }

        var windowWidth = 0 ;
        var scale = 1;
        if (CC_WECHATGAME)
        {
            wx.getSystemInfo({
            success: function(res) {
                
            // console.log(res.model)
            // console.log(res.pixelRatio)
            // console.log(res.windowWidth)
            windowWidth = res.windowWidth;
            // console.log(res.windowHeight)
            // console.log(res.screenWidth)
            // console.log(res.screenHeight)
            // console.log(res.language)
            // console.log(res.version)
            // console.log(res.platform)

            }
            });  

            if(windowWidth - 360 > 0)
            {
                scale = 1 - (windowWidth - 360)/360;
               node.scale = scale; 
            }

            if(windowWidth - 360 < 0)
            {
                scale = 1 + (360 - windowWidth )/360;
                node.scale = scale; 
            }
        } 

    },

    'GetDateString':function()
    {
        var d = new Date();
        var timeStr = "";
        var str = d.getMonth();
        var str = d.getDate();
        timeStr += str + ":";
        str = d.getHours();
        timeStr += (str.length == 1 ? "0" + str : str) + ":";
        str = d.getMinutes();
        timeStr += (str.length == 1 ? "0" + str : str) + ":";
        str = d.getSeconds();
        timeStr += str.length == 1 ? "0" + str : str;
        timeStr += ":";
        str = d.getMilliseconds()
        timeStr += str;
        
        timeStr = "[" + timeStr + "]";
        return timeStr;
    },
    'InspectPrint':function(pre,data)
    {

        var util = require("util")
        var timeStr = this.GetDateString();

        if(data==undefined)
        {
            console.log(timeStr + " " + util.inspect(pre,{depth:null})); //depth:null 展开全部层级

        }
        else 
        {
            console.log(timeStr + " " + pre + util.inspect(data,{depth:null})); //depth:null 展开全部层级

        }
    },




    'Print':function(str)
    {
        var timeStr = this.GetDateString();
        console.log(timeStr + " " + str );
    },

    'H5SDKReport':function (r_type,card_ID,slot_ID,order_ID,iAction_Id,ext)
    {
        // if(CC_WECHATGAME)
        // {
        //     H5SDK.report(r_type, {
        //         vRoleID: DataModelManager.getModel('PlayerInfoModel').selfRoleId,
        //         cardID: card_ID,
        //         slotID: slot_ID,
        //         orderID: order_ID,
        //         iActionId: iAction_Id,
        //         extend: ext
        //     });
        // }

    },
    
    'Uint8ArrayToString':function (fileData){

        var dataString = "";
        for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
        }
    return dataString
  },
  'stringToUint8Array':function (str){
    var arr = [];
    for (var i = 0, j = str.length; i < j; ++i) {
      arr.push(str.charCodeAt(i));
    }
   
    var tmpUint8Array = new Uint8Array(arr);
    return tmpUint8Array
  },

  'str2ab':function (str) {
    var buf = new ArrayBuffer(str.length * 2); // 每个字符占用2个字节
    var bufView = new Uint16Array(buf);
    for (var i = 0, strLen = str.length; i < strLen; i++) {
      bufView[i] = str.charCodeAt(i);
    }
    return buf;
  },

  'utf16ToUtf8' : function (s) {
	if(!s){
		return;
	}
	
	var i, code, ret = [], len = s.length;
	for(i = 0; i < len; i++){
		code = s.charCodeAt(i);
		if(code > 0x0 && code <= 0x7f){
			//单字节
			//UTF-16 0000 - 007F
			//UTF-8  0xxxxxxx
			ret.push(s.charAt(i));
		}else if(code >= 0x80 && code <= 0x7ff){
			//双字节
			//UTF-16 0080 - 07FF
			//UTF-8  110xxxxx 10xxxxxx
			ret.push(
				//110xxxxx
				String.fromCharCode(0xc0 | ((code >> 6) & 0x1f)),
				//10xxxxxx
				String.fromCharCode(0x80 | (code & 0x3f))
			);
		}else if(code >= 0x800 && code <= 0xffff){
			//三字节
			//UTF-16 0800 - FFFF
			//UTF-8  1110xxxx 10xxxxxx 10xxxxxx
			ret.push(
				//1110xxxx
				String.fromCharCode(0xe0 | ((code >> 12) & 0xf)),
				//10xxxxxx
				String.fromCharCode(0x80 | ((code >> 6) & 0x3f)),
				//10xxxxxx
				String.fromCharCode(0x80 | (code & 0x3f))
			);
		}
	}
	
	return ret.join('');

    },


    'utf8ToUtf16':function (s) {
        if(!s){
            return;
        }
        
        var i, codes, bytes, ret = [], len = s.length;
        for(i = 0; i < len; i++){
            codes = [];
            codes.push(s.charCodeAt(i));
            if(((codes[0] >> 7) & 0xff) == 0x0){
                //单字节  0xxxxxxx
                ret.push(s.charAt(i));
            }else if(((codes[0] >> 5) & 0xff) == 0x6){
                //双字节  110xxxxx 10xxxxxx
                codes.push(s.charCodeAt(++i));
                bytes = [];
                bytes.push(codes[0] & 0x1f);
                bytes.push(codes[1] & 0x3f);
                ret.push(String.fromCharCode((bytes[0] << 6) | bytes[1]));
            }else if(((codes[0] >> 4) & 0xff) == 0xe){
                //三字节  1110xxxx 10xxxxxx 10xxxxxx
                codes.push(s.charCodeAt(++i));
                codes.push(s.charCodeAt(++i));
                bytes = [];
                bytes.push((codes[0] << 4) | ((codes[1] >> 2) & 0xf));
                bytes.push(((codes[1] & 0x3) << 6) | (codes[2] & 0x3f));			
                ret.push(String.fromCharCode((bytes[0] << 8) | bytes[1]));
            }
        }
        return ret.join('');
    },

    'delRight': function(buf) {
        var u16array = new Uint16Array(buf);
        if((u16array[u16array.length-1])!=0)
        {
            return u16array
        }
        for (var i = u16array.length - 1; i >= 0; i--) {
            if (u16array[i] != 0) {
                var arr1 = u16array.slice(0, i + 1);
                return arr1;
            }
        }
        return null;
    },

    'ab2str':function(buf) {
        var arr = Common.delRight(buf);
        if (!arr) {
            return '';
        } else {
            var decodedString = String.fromCharCode.apply(null, arr); 
            // console.log("ab2str:" + decodedString);
            return decodedString;
        }
    },
  'version':function(p,m,s,b){
    var v = 0

    if (p != null) 
        v = v | (p<<24)

    if (m != null) 
        v = v | (m<<16)

    if (s != null) 
        v = v | (s<<8)

    if (b != null) 
        v = v | b

    return v

  },
  'putString':function(index,viewData,str,length)
  {
    var len = length
    var strLen =  str.length
    if(len==undefined||len==null)
    {
        len = str.length
    }
    for (var i = 0; i < len; i++) 
    {
        if(i<strLen)
        {
            viewData.setUint16(index,str.charCodeAt(i),Common.littleEndian);
        }
        index += 2
    }
    return index
  },
  'getString':function(buf,readPos,size)
  {
    var arraybuffer = buf.slice(readPos, readPos + size)
    return  Common.ab2str(arraybuffer)
  },
  'readint64BE':function(buf,readPos)
  {
    var arraybuffer = buf.slice(readPos, readPos + 8)
    var big = new Int64BE(arraybuffer);

    return big.toNumber()
  },
  'readint64LE':function(buf,readPos)
  {
    var arraybuffer = buf.slice(readPos, readPos + 8)
    var big = new Int64LE(arraybuffer);

    return big.toNumber()
  },
  'readint64':function(buf,readPos)
  {
    if(Common.littleEndian)
    {
        return Common.readint64LE(buf,readPos)
    }
    else
    {
        return Common.readint64BE(buf,readPos)
    }
  },


    '_loadImage':function(url, callback){
        cc.loader.load({url: url, type: "jpeg"}, (err, tex)=>{
            if (err){
                cc.error(err);
            } else {
                callback(tex);
            }
        });
    },

    'loadImage':function(url, callback){
        // Web平台直接加载
        if (!cc.sys.isNative){
            this._loadImage(url, callback);
            return;
        }
    
        let dirpath = jsb.fileUtils.getWritablePath() + "TclGameImg/";
        cc.log("dirpath: " + dirpath);
    
        // let md5 = require("./encrypt/Md5");
        // let md5Url = md5.md5_hex(url);
        var tempIndex = url.lastIndexOf("\/");
        var fileName = url.substring(tempIndex + 1);
        let filePath = dirpath + fileName
        cc.log("filepath: " + filePath);
    
        function loadEnd() {
            cc.loader.load(filePath, (err, tex)=>{
                if (err){
                    cc.error(err);
                } else {
                    callback(tex);
                }
            });
        }
    
        if (jsb.fileUtils.isFileExist(filePath)){
            cc.log("Remote img is find: " + filePath);
            loadEnd();
            return;
        }
    
        let saveFile = function (data) {
            if (data && typeof data !== "undefined"){
                if (!jsb.fileUtils.isDirectoryExist(dirpath)){
                    jsb.fileUtils.createDirectory(dirpath);
                } else {
                    cc.log("路径 " + dirpath + "已经存在。");
                }
    
                if(jsb.fileUtils.writeDataToFile(new Uint8Array(data), filePath)){
                    cc.log("Remote img save succeed.");
                    loadEnd();
                }else {
                    cc.log("Remote img save failed.");
                }
            } else {
                cc.log("Remote img download failed.");
            }
        };
    
        let xhr = cc.loader.getXMLHttpRequest();
        xhr.onreadystatechange = function () {
            cc.log("xhr.readyState: " + xhr.readyState);
            cc.log("xhr.status: " + xhr.status);
            if (xhr.readyState === 4){
                if (xhr.status === 200){
                    saveFile(xhr.response);
                } else {
                    saveFile(null);
                }
            }
        }.bind(this);
        xhr.responseType = 'arraybuffer';
        xhr.open('GET', url, true);
        xhr.send();
    },
};


export default Common;