'use strict';

var Fs = require("fire-fs");
var Path = require("fire-path");

function updateMainJs (event, callback) {
    
    var root = Path.normalize(event.dest);
    var url = Path.join(root, "main.js");
    Editor.log(url);
    Editor.log(event.actualPlatform);
    Editor.log(callback);
    if (event.actualPlatform !== "web-mobile"){
        Editor.log("------------------开始修改main.js-----------------")
        Fs.readFile(url, "utf8", function (err, data) {
            if (err) {
                throw err;
            }

            var newStr =
                "if (window.jsb) { \n" +
                "    var hotUpdateSearchPaths = localStorage.getItem('HotUpdateSearchPaths'); \n" +
                "    if (hotUpdateSearchPaths) { \n" +
                "        console.log('hotUpdateSearchPaths-----: ' + hotUpdateSearchPaths);\n" +
                "        jsb.fileUtils.setSearchPaths(JSON.parse(hotUpdateSearchPaths)); \n" +
                "    }\n" +
                "}\n"+
                "window.boot = function () {\n"

            var newData = data.replace("window.boot = function () {", newStr);
            Fs.writeFile(url, newData, function (error) {
                if (err) {
                    throw err;
                }
                Editor.log("SearchPath updated in built main.js for hot update");
            });
            callback();
        });
    } else {
        Editor.log("------------------开始修改index.html-----------------")
        url = Path.join(root, "index.html");
        Editor.log(url);
        var cssName = "style-mobile.css";
        Fs.readFile(url, "utf8", function (err, data) {
            if (err) {
                throw err;
            }

            var newStr = "(function () {\n"+
            "var reg = new RegExp('(^|&)' + 'inviteCode' + '=([^&]*)(&|$)');\n"+
            // 查询匹配 substr(1)删除? match()匹配
            "var inviteCode = window.location.search.substr(1).match(reg);\n"+
            "if (inviteCode != null) {\n"+
            "  window.DelegateInviteKey = unescape(inviteCode[2]);\n"+
            "}\n"+
            "var urls = window.location.href.split('?');\n"+
            "var replaceUrl = urls.length > 1 ? urls[0] : window.location.href;\n"+
            "history.replaceState(null, '', replaceUrl);\n";

            var newIndexData = data.replace("(function () {", newStr);


            var newStr2 = "</canvas>\n"+
            "<div id=\"swipe\"></div>\n"+
            "<div id=\"mask\"></div>\n"+
            "<div id=\"tip\"> </div>\n"+
            "<div id=\"tip2\"> </div>\n"+
            "<div id=\"button\"></div>";
            var newIndexData2 = newIndexData.replace("</canvas>", newStr2);
            Fs.writeFile(url, newIndexData2, function (error) {
                if (err) {
                    throw err;
                }
                Editor.log("SearchPath updated in built index.html for hot update");
            
                var str = 'main.'
                var S1 = newIndexData2.split(str)
                Editor.log("s1!-"+S1);
                var mainName = str + S1[1].substring(0,5) + '.js'
                Editor.log("S1[1].substring(0,5)!-"+S1[1].substring(0,5));
                var url2 = Path.join(root, mainName)
                Editor.log("------------------开始修改main.js-----------------" + mainName + url2)
                Fs.readFile(url2, "utf8", function (err, maindata) {
                    if (err) {
                        throw err;
                    }
                    var newStr =
                        "var isMobile = navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i) != null;\n"+
                        "var isiPad = navigator.userAgent.match(/iPad/i) != null;\n"+
                        "var isiPhone = navigator.userAgent.match(/iPhone|iPod/i) != null;\n"+
                        "var isBaidu = navigator.userAgent.match(\"baidu\") != null;\n"+
                        "var isQQ = navigator.userAgent.match(\"MQQBrowser\") != null;\n"+
                        "var isFirefox = navigator.userAgent.match(\"FxiOS\") != null;\n"+
                        "var isUC = navigator.userAgent.indexOf(\"UCBrowser\") != -1;\n"+
                        "var isChrome = navigator.userAgent.match(\"CriOS\") != null;\n"+
                        "var isXiaomi = navigator.userAgent.match(\"XiaoMi\") != null;\n"+
                        "var isSogou = navigator.userAgent.match(\"Sogou\") != null;\n"+
                        "var isSafari = navigator.userAgent.match(\"Safari\") && !isBaidu && !isFirefox && !isQQ && !isChrome && !isUC && !isXiaomi;\n"+
                        "var isAndroid = /android/i.test(navigator.userAgent || navigator.vendor || window.opera);\n"+
                        "var isMask = false\n"+
                        "var isHor = false\n"+
                        "var newC = 0;\n"+
                        "window.boot = function () {\n"+    
                        "    window.addEventListener('scroll', scroll, false);\n"+
                        "   function scroll() {\n"+
                        "       if (window.orientation == 90 || window.orientation == -90) {\n"+
                        "           if(window.scrollY > 100){\n"+
                        "               showMask(false)\n"+
                        "           }\n"+
                        "       }\n"+
                        "       if (document.body.clientHeight >= window.innerHeight && isMask && isSafari) {\n"+
                        "            return;\n"+
                        "       }\n"+
                        "       if (window.scrollY < this.lastY) {\n"+
                        "           window.scrollTo(0, (document.body.clientHeight - window.innerHeight) / 2);\n"+
                        "        }\n"+
                        "       this.lastY = window.scrollY;\n"+
                        "   }\n"+
                        "   window.onload = function(){\n"+
                        "   showAndroidMask(false)\n"+
                        "    }\n"+
                        "   window.onresize = function(){\n"+
                        "       if (window.orientation == 180 || window.orientation == 0) {\n"+
                        "       }\n"+
                        "       if (window.orientation == 90 || window.orientation == -90) {\n"+
                        "           checkAndroidFullScreen()\n"+
                        "           newC = (document.body.clientHeight - window.innerHeight) / 2;\n"+
                        "           if (isSafari && isHor && !isAndroid) {\n"+
                        "               resetScreenSize();\n"+
                        "            }\n"+
                        "            isHor = true\n"+
                        "           var isCancel = isCancelType()\n"+
                        "           if(!isCancel){\n"+
                        "               showMask(false)\n"+
                        "               return\n"+
                        "           }\n"+
                        "           isMask = window.innerHeight - document.body.clientHeight >= 0 ?  false : true \n"+
                        "       }\n"+
                        "       if(window.scrollY > 0) {\n"+
                        "           window.scrollTo(0,0);\n"+
                        "       }\n"+
                        "       showMask(isMask)\n"+
                        "   }.bind(this)\n"+
                        "   function isCancelType(){\n"+
                        "       var agentStr = navigator.userAgent.toLowerCase()\n"+
                        "       if(cc.sys.browserType == cc.sys.BROWSER_TYPE_CHROME || agentStr.indexOf(\"crios\") != -1\n"+
                        "           || cc.sys.browserType == cc.sys.BROWSER_TYPE_FIREFOX || agentStr.indexOf(\"fxios\") != -1 || isUC\n"+
                        "           ){\n"+
                        "           return false\n"+
                        "       }\n"+
                        "       return true\n"+
                        "   }\n"+
                        "   function resetScreenSize(_Size){\n"+
                        "       var scaleWidthToHeight = (document.body.clientHeight / window.innerHeight);\n"+
                        "       cc.view.setDesignResolutionSize(1334 * scaleWidthToHeight, 750 * scaleWidthToHeight, cc.ResolutionPolicy.SHOW_ALL);\n"+
                        "   }\n"+
                        "   function rotate() {\n"+
                        "       showTip(false)\n"+
                        "       showMask(false)\n"+
                        "       if (window.orientation == 180 || window.orientation == 0) {\n"+
                        "           console.log(\"竖屏\")\n"+
                        "           isHor = true\n"+
                        "           showTip(true)\n"+
                        "       }\n"+
                        "       if (window.orientation == 90 || window.orientation == -90) {\n"+
                        "            console.log('横屏')\n"+
                        "           this.FraWidth = window.innerWidth\n"+
                        "          checkAndroidFullScreen()\n"+
                        "       }\n"+
                        "   }\n"+
                        "   window.addEventListener(\"load\", rotate, false);\n"+
                        "   window.addEventListener(\"onorientationchange\" in window ? \"orientationchange\" : 'resize', rotate, false);\n"+
                        "   function showTip(_bool){\n"+
                        "       var splash = document.getElementById('swipe');\n"+
                        "       if (cc.director.getScene() && cc.director.getScene()._name === `delegateStore`) {\n"+
                        "           _bool = false;\n"+
                        "        }\n"+
                        "       if(_bool){\n"+
                        "           splash.style.display = 'block';\n"+
                        "       }else{\n"+
                        "           splash.style.display = 'none'\n"+
                        "       }\n"+
                        "   }\n"+
                        "   var m_Mask = document.getElementById('mask');\n"+
                        "   var btn = document.getElementById('button');\n"+
                        "   var tip = document.getElementById('tip');\n"+
                        "   var tip2 = document.getElementById('tip2');\n"+
                        "   btn.addEventListener(\"click\",onCancel,false)\n"+
                        "   tip2.addEventListener(\"mousedown\",onMask,false)\n"+
                        "   function onCancel(_event) {\n"+
                        "       showMask(false)\n"+
                        "       window.scrollTo(0, newC);\n"+
                        "   }\n"+
                        "   function showMask(_bool){\n"+
                        "       console.log('isAndroid'+ isAndroid)\n"+
                        "       if(isAndroid){\n"+
                        "           //m_Mask.style.display = \"none\"\n"+
                        "           //btn.style.display = \"none\"\n"+
                        "           //tip.style.display = \"none\"\n"+
                        "           return\n"+
                        "       }\n"+
                        "       isMask = _bool\n"+
                        "       console.log('showMask'+ _bool)\n"+
                        "       if(_bool){\n"+
                        "           m_Mask.style.display = 'block'\n"+
                        "           btn.style.display = 'block'\n"+
                        "           tip.style.display = 'block'\n"+
                        "       }else{\n"+
                        "           m_Mask.style.display = \"none\"\n"+
                        "           btn.style.display = \"none\"\n"+
                        "           tip.style.display = \"none\"\n"+
                        "           tip2.style.display = \"none\"\n"+
                        "       }\n"+
                        "   }\n"+
                        "function IsFullScreen() {\n"+
                        "   var isFullscreen = document.isFullScreen || document.mozIsFullScreen || document.webkitIsFullScreen || document.fullscreen || \n"+
                        "   document.mozFullScreen ||                         \n"+
                        "   document.webkitIsFullScreen ||       \n"+
                        "   document.webkitFullScreen || \n"+
                        "   document.msFullScreen \n"+
                        "    return isFullscreen\n"+
                        "}\n"+
                        "function checkAndroidFullScreen(){\n"+
                        "    if(!isAndroid) return\n"+
                        "    console.log('checkAndroidFullScreen')\n"+
                        "   if(IsFullScreen()){\n"+
                        "        showAndroidMask(false)\n"+
                        "    }else{\n"+
                        "       showAndroidMask(true)\n"+
                        "    }\n"+
                        "}\n"+
                        "function showAndroidMask(_bool) {\n"+
                        "   if(!isAndroid){\n"+
                        "      _bool = false\n"+
                        "   }\n"+
                        "    if(_bool && isSogou) return\n"+
                        "    console.log('showAndroidMask'+ _bool)\n"+
                        "   if(_bool){\n"+
                        "       m_Mask.style.display = 'block'\n"+
                        "       btn.style.display = 'block'\n"+
                        "       tip2.style.display = 'block'\n"+
                        "   }else{\n"+
                        "       m_Mask.style.display = 'none'\n"+
                        "       btn.style.display = 'none'\n"+
                        "       tip.style.display = 'none'\n"+
                        "       tip2.style.display = 'none'\n"+
                        "   }\n"+
                        "}\n"+
                        "function onMask() {\n"+
                        "    console.log('onMask')\n"+
                        "    if(!isAndroid) return\n"+
                        "   var ele = document.documentElement;\n"+
                        "   try {\n"+
                        "       if (ele.requestFullscreen) {\n"+
                        "            ele.requestFullscreen();\n"+
                        "        } else if (ele.mozRequestFullScreen) {\n"+
                        "            ele.mozRequestFullScreen();\n"+
                        "        } else if (ele.webkitRequestFullscreen) {\n"+
                        "           ele.webkitRequestFullscreen();\n"+
                        "        } else if (ele.msRequestFullscreen) {\n"+
                        "           ele.msRequestFullscreen();\n"+
                        "        }\n"+
                        "       showAndroidMask(false)\n"+
                        "   } catch (error) {\n"+
                        "       showAndroidMask(false)\n"+
                        "    }\n"+
                        "}\n"
        
                    var newMainData = maindata.replace("window.boot = function () {", newStr);
                    // 取消web端自动全屏
                    newMainData = newMainData.replace("indexOf(cc.sys.browserType) < 0);", "indexOf(cc.sys.browserType) < 0);cc.view.enableAutoFullScreen(false);");
                    Fs.writeFile(url2, newMainData, function (error) {
                        if (err) {
                            throw err;
                        }
                        Editor.log("SearchPath updated in built main.js for hot update");
                        var str = "style-mobile";
                        var end = 'css"/>';
                        var s1 = newIndexData2.split(str);
                        var s2 = newIndexData2.split(end);
                        cssName = s2[0].slice(s1[0].length, s2[0].length) + "css";

                        url = Path.join(root, cssName);
                        Editor.log(url);
                        Fs.readFile(url, "utf8", function (err, styleData) {
                            if (err) {
                                throw err;
                            }
                            var oldStr = "height: 15px;";
                            var newStr = "height: 0px;";
                
                            var newStyleData = styleData.replace(oldStr, newStr);
                
                            var oldStr2 = "box-shadow: 0 1px 5px #000 inset, 0 1px 0 #444";
                            var newStr2 = "box-shadow: 0 0px 0px #000 inset, 0 0px 0 #444;";
                
                            var newStyleData2 = newStyleData.replace(oldStr2, newStr2);

                            var oldStr3 = "#splash {";
                            var newStr3 = "#swipe {\n"+
                                "position: fixed;\n"+
                                "top: 0;\n"+
                                "left: 0;\n"+
                                "width: 100%;\n"+
                                "height: 100%;\n"+
                                " background: #171717 url(./swipe.gif) no-repeat center;\n"+
                                " background-size: 60%;\n"+
                                " background-color:#000000;\n"+
                                " }\n"+
                                " #mask {\n"+
                                " position: absolute;\n"+
                                " top: 0;\n"+
                                " left: 0;\n"+
                                " width: 100%;\n"+
                                " height: 120%;\n"+
                                " opacity:1;\n"+
                                " background-size: 20%;\n"+
                                " background-color:#000000;\n"+
                                " }\n"+
                                "#tip {\n"+
                                "   position: absolute;\n"+
                                "   bottom: 20%;\n"+
                                "   left: 0;\n"+
                                "   width: 100%;\n"+
                                "   height: 100%;\n"+
                                "   opacity:1;\n"+
                                "   background: #171717 url(./swipe2.gif) no-repeat center;\n"+
                                "   background-size: 20%;\n"+
                                "   background-color:#000000;\n"+
                                " }\n"+
                                "#tip2 {\n"+
                                "   position: absolute;\n"+
                                "    bottom: 25%;\n"+
                                "   left: 3%;\n"+
                                "   width: 100%;\n"+
                                "   height: 100%;\n"+
                                "   opacity:1;\n"+
                                "   background: #171717 url(./swipe3.gif) no-repeat center;\n"+
                                "   background-size: 20%;\n"+
                                "   background-color:#000000;\n"+
                                " }\n"+
                                " #button {\n"+
                                "   position: absolute;\n"+
                                "   bottom: 25%;\n"+
                                "   left: 43%;\n"+
                                "   width: 15%;\n"+
                                "   height: 12%;\n"+
                                "   opacity:1;\n"+
                                "   background: #171717 url(./cancel.png) no-repeat center;\n"+
                                "   background-size: 100%;\n"+
                                " }\n"+
                                " #splash {";
                
                            var newStyleData3 = newStyleData2.replace(oldStr3, newStr3);
                            Fs.writeFile(url, newStyleData3, function (error) {
                                if (err) {
                                    throw err;
                                }
                                Editor.log("SearchPath updated in built index.html for hot update");
                                callback();
                            });
                        });
                    });
                });
            });
        });

       
    }
}

module.exports = {
    load: function () {
        // 当 package 被正确加载的时候执行
         Editor.Builder.on('build-finished',updateMainJs)
    },

    unload: function () {
        // 当 package 被正确卸载的时候执行
        Editor.Builder.removeListener('build-finished', updateMainJs);
    },

    messages: {
        // 'build-finished': 
        getBuildOptions(event) {
            event.reply(null, buildOptions);
        }
    }
};