/**
 *官网静态资源直接上传到测试环境
 **/
var path = require('path');
var settings = require('../settings');
var jsdom = require('jsdom');
var xtpl = require('xtpl');
var fs = require('fs');
var iconv = require('iconv-lite');
var _ = require('../../lib/util');

module.exports = function (hoo, root, media, releaseSource) {

  var projectFiles = hoo.get('project.files');
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.pop();
  projectFiles.push('/opening/*.html');
  hoo.set('project.files', projectFiles);

  var defineConfig = {};
  /*main.htm模板内容*/
  var mainHtmlWindow = '';
  /*开服页模板内容*/
  var openingHtmlWindow = '';
  /*选服页模板内容*/
  var serverListHtmlWindow = '';
  /*手机官网*/
  var wapHtmlWindow = '';
  /*手机内页*/
  var wapContentHtmlWindow = '';

  var openingHtmlCreated = fs.existsSync(path.join(process.cwd(), settings.wwwTplsDir, root, 'opening', 'index.htm'));

  var toUploadOpeningFiles = [];

  var prePromise = new Promise(function (resolve) {
    jsdom.env(
      path.join(process.cwd(), settings.wwwTplsDir, root, 'main.htm'),
      {defaultEncoding: 'UTF-8'},
      function (err, window) {
        mainHtmlWindow = window;
        resolve();
      }
    );
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'server_list.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          serverListHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'wap/index.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          wapHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.wwwTplsDir, root, 'wap/article/content.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          wapContentHtmlWindow = window;
          resolve();
        }
      );
    });
  }).then(function () {
    return new Promise(function (resolve) {
      jsdom.env(
        path.join(settings.openingRoot, settings.openingTemplatePath, root, 'index.htm'),
        {defaultEncoding: 'UTF-8'},
        function (err, window) {
          openingHtmlWindow = window;
          resolve();
        }
      );
    });
  });

  var hooMatches = hoo.media(media, defineConfig).match('**', {
      useHash: !!releaseSource ? false : true,
      useCache: true
    })
      .match('/opening/*.html', {
        isInline: false,
        release: '$0'
      })
      .match('/css/main/**.{css,scss}', {
        packTo: '/static/bundle.css'
      })
      .match('/css/*main.{css,scss}', {
        packTo: '/static/bundle.css'
      })
      .match('/css/app/**.{css,scss}', {
        useSprite: true
      })
      .match('/static/bundle.css',{
        useSprite: true
      })
      .match('/opening/**.{css,scss}', {
        useSprite: true
      })
      .match('**.{png,jpg,mp4}', {
        domain: "http://" + path.join(settings.wwwDeployDomain, root).replace(/\\/g, '/')
      })
      .match('/opening/**', {
        domain: false
      })
      .match('/opening/**/(*.{css,scss})', {
        domain: '/static',
        release: path.join('css', '1/') + '$1$2'
      })
      .match('/opening/**/(*.{png,jpg})', {
        domain: '/static',
        release: path.join('images', '1/') + '$1$2'
      })
      .match('/css/images/extras/**', {
        useHash: false
      })
      .match('::package', {
        packager: hoo.plugin('map', {
          useTrack: false// 是否输出路径信息,默认为 true
        }),
        // 分析 __RESOURCE_MAP__ 结构，来解决资源加载问题
        postpackager: hoo.plugin('loader', {
          resourceType: 'amd',
          useInlineMap: true
        }, 'prepend')
      })
      .match('**', {
        deploy: [
          hoo.plugin('skip-packed', {
            // 配置项
            skipPackedToPkg: true,//是否过滤掉被打包的文件
            skipPackedToAIO: true,//是否过滤掉被 AllInOne 打包的文件
            skipPackedToCssSprite: true,//是否过滤掉被 css sprite 合并的文件。
            ignore: []//即便设置了过滤，但是如果目标文件 ignore 列表中，还是不会被过滤。glob 语法，数组或者字符串。
          }),
          function (options, modified, total, next) {
            var i = modified.length - 1;
            var file;

            while ((file = modified[i--])) {
              if (file.isHtmlLike) {
                modified.splice(i + 1, 1);
              } else if (file.isJsLike) {
                (function (file) {
                  prePromise = prePromise.then(function () {
                    return new Promise(function (resolve) {
                      var jsLoader1 = mainHtmlWindow.document.getElementById("jsLoader");
                      var jsLoader2 = serverListHtmlWindow.document.getElementById("jsLoader");
                      jsLoader1 && (jsLoader1.src = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                      jsLoader2 && (jsLoader2.src = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                      resolve();
                    })
                  })
                })(file);
              } else if (file.isCssLike) {
                (function (file) {
                    if (file.subdirname.indexOf('opening') !== -1) {
                      toUploadOpeningFiles.push(file);
                      modified.splice(i + 1, 1);
                      prePromise = prePromise.then(function () {
                          return new Promise(function (resolve) {
                            var cssLoader = openingHtmlWindow.document.getElementById("cssLoader");
                            cssLoader && (cssLoader.href = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                            resolve();
                          })
                        }
                      );
                    } else if (file.map.uri.indexOf('bundle') !== -1) {
                      prePromise = prePromise.then(function () {
                        return new Promise(function (resolve) {
                          var cssLoader1 = mainHtmlWindow.document.getElementById("cssLoader");
                          var cssLoader2 = serverListHtmlWindow.document.getElementById("cssLoader");
                          cssLoader1 && (cssLoader1.href = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                          cssLoader2 && (cssLoader2.href = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                          resolve();
                        })
                      });
                    } else if (file.map.uri.indexOf('app') !== -1) {
                      prePromise = prePromise.then(function () {
                        return new Promise(function (resolve) {
                          var cssLoader1 = wapHtmlWindow.document.getElementById("cssLoader");
                          var cssLoader2 = wapContentHtmlWindow.document.getElementById("cssLoader");
                          cssLoader1 && (cssLoader1.href = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                          cssLoader2 && (cssLoader2.href = 'http://' + path.join(settings.wwwDeployDir, root, file.map.uri).replace(/\\/g, '/'));
                          resolve();
                        })
                      });
                    }
                  })(file);
              } else if (file.subpath.indexOf('opening') !== -1) {
                toUploadOpeningFiles.push(file);
                modified.splice(i + 1, 1);
              }
            }
            next();
          },
          hoo.plugin('http-push', {
            receiver: settings.wwwUploadScript,
            to: path.join('/www', settings.wwwDeployDir, root)// 注意这个是指的是测试机器的路径，而非本地机器
          })
          // require('../../lib/httpUploader')(toUploadOpeningFiles,root)
        ]
      })
    ;

  //不混淆和压缩代码，提供清晰格式的代码给合作平台开发者使用
  if (!releaseSource) {
    hooMatches.match('*.{css,scss}', {
      optimizer: hoo.plugin('clean-css', {})
    })
      .match('*.js', {
        optimizer: hoo.plugin('uglify-js')
      })
  }

  hoo.on('deploy:end', function () {

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'opening', 'index.htm'), openingHtmlWindow.document.documentElement.outerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        if(openingHtmlCreated){
          fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'main.htm'), mainHtmlWindow.document.body.innerHTML, function (err) {
            if (err) {
              hoo.log.error(err);
              return;
            }
            resolve();
          });
        }else{
          resolve();
        }
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'server_list.htm'), serverListHtmlWindow.document.body.innerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'wap/index.htm'), wapHtmlWindow.document.documentElement.outerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        fs.writeFile(path.join(process.cwd(), settings.wwwTplsDir, root, 'wap/article/content.htm'), wapContentHtmlWindow.document.documentElement.outerHTML, function (err) {
          if (err) {
            hoo.log.error(err);
            return;
          }
          resolve();
        });
      });
    });

    prePromise.then(function () {
      console.log('---------------完成-----------------');
    });
  });
};
