/*
 * 提交源码目录下的文件到svn
 * */
var Client = require('svn-spawn');
var path = require('path');
var settings = require('../conf/settings');
module.exports = function (hoo, toAddImg1Files, toAddOpeningFiles, root, title) {

  var tplsClient = new Client({
    cwd: path.join(process.cwd(), settings.wwwTplsDir, root)
  });
  var img1Client = new Client({
    cwd: path.join(process.cwd(), settings.wwwDeployDir, root)
  });

  var openingClient = new Client({
    cwd: path.join(settings.openingRoot)
  });

  var prePromise = Promise.resolve();

  /*
   * 官网模板文件自动提交
   * */
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      tplsClient.getStatus(function (err, data) {
        if (data.length === 0) {
          hoo.log.info(path.join(settings.wwwTplsDir, root) + '目录下内容无修改');
          resolve();
          return;
        }
        var status = data[0]['wc-status'].$.item;
        console.log('\n');
        if (['none', 'unversioned'].indexOf(status) !== -1) {
          tplsClient.addLocal(function (err) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            tplsClient.commit(title + '----HOO工程化框架自动提交', function (err) {
              hoo.log.info(path.join(settings.wwwTplsDir, root) + "目录下文件提交成功");
              resolve();
            });
          });
        } else if (['modified', 'added'].indexOf(status) !== -1) {
          tplsClient.commit(title + '----HOO工程化框架自动提交', function (err) {
            hoo.log.info(path.join(settings.wwwTplsDir, root) + "目录下文件提交成功");
            resolve();
          });
        } else {
          hoo.log.error('未知错误')
        }
      });
    });
  });
  /*
   * img1下资源是否提交gamekey目录
   * */
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      img1Client.getStatus(function (err, data) {
        if (err) {
          hoo.log.debug(err);
          return;
        }
        if (data.length === 0) {
          hoo.log.info(path.join(settings.wwwDeployDir, root) + '目录下内容无修改');
          return;
        }
        var item1 = data[0].$;
        if (item1.path !== '.') {
          resolve();
          return;
        }
        var status = data[0]['wc-status'].$.item;
        if (['none', 'unversioned'].indexOf(status) !== -1) {
          img1Client.add(['.', '--non-recursive', '--parents'], function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            resolve();
          })
        } else if (['missing'].indexOf(status) !== -1) {
          img1Client.del(['.'], function (err) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            resolve();
          })
        } else if (['modified'].indexOf(status) !== -1) {
          resolve();
        } else if (['added'].indexOf(status) !== -1) {
          resolve();
        } else {
          hoo.log.error("未知错误");
        }
      });
    });
  });

  /*
   * img1下资源提交
   * */
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      function addFilePromise(file) {
        return new Promise(function (resolve) {
          img1Client.getStatus(path.relative(root, file.path), function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            if (data.length === 0) {
              resolve();
              return;
            }
            var item1 = data[0].$;
            if (item1.path !== path.relative(root, file.path)) {
              resolve();
              return;
            }
            var status = data[0]['wc-status'].$.item;
            // add
            if (['none', 'unversioned'].indexOf(status) !== -1) {
              img1Client.add([path.relative(root, file.path), '--non-recursive', '--parents'], function (err, data) {
                if (err) {
                  hoo.log.err(err);
                  return;
                }
                resolve();
              })
            }
            // delete
            else if (['missing'].indexOf(status) !== -1) {
              img1Client.del(path.relative(root, file.path), function (err) {
                if (err) {
                  hoo.log.error(err);
                  return;
                }
              });
            } else if (['modified'].indexOf(status) !== -1) {
              resolve();
            } else if (['added'].indexOf(status) !== -1) {
              resolve();
            } else {
              hoo.log.error("未知错误");
            }
          });
        })
      }

      var prevPromise = Promise.resolve();//初始化一个总能被解析的Promise

      toAddImg1Files.forEach(function (file) {
        prevPromise = prevPromise.then(function () {//每次迭代时prevPromise发生改变
          return addFilePromise(file);//返回一个新的Promise
        })
      });

      prevPromise.then(function () {
        hoo.log.info('目录:' + path.join(settings.wwwDeployDir, root) + '下所有文件-Added To SVN');
        img1Client.commit(title + '----HOO工程化框架自动提交', function (err) {
          if (err) {
            // hoo.log.error(err);
            return;
          }
          hoo.log.info(path.join(settings.wwwDeployDir, root) + "目录下文件提交成功");
          resolve();
        });
      });
    })
  });

  /*
   * 开服页文件提交
   * */
  prePromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      var toAddPath = [];

      function addFilePromise(file) {
        var filePath = (file.path.indexOf('template') !== -1) ? file.path : path.join(settings.openingStaticPath, file.path);
        return new Promise(function (resolve) {
          openingClient.getStatus(filePath, function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            if (data.length === 0) {
              resolve();
              return;
            }

            /*
             * 如果当前目录已提交，跳过此步骤
             * */
            var item1 = data[0].$;
            if (item1.path !== filePath) {
              resolve();
              return;
            }
            var status = data[0]['wc-status'].$.item;
            // add
            if (['none', 'unversioned'].indexOf(status) !== -1) {
              openingClient.add([filePath, '--non-recursive', '--parents'], function (err, data) {
                if (err) {
                  hoo.log.err(err);
                  return;
                }
                resolve();
                toAddPath.push(filePath);
              })
            }
            // delete
            else if (['missing'].indexOf(status) !== -1) {
              openingClient.del(filePath, function (err) {
                if (err) {
                  hoo.log.error(err);
                  return;
                }
              });
            } else if (['modified'].indexOf(status) !== -1) {
              toAddPath.push(filePath);
              resolve();
            } else if (['added'].indexOf(status) !== -1) {
              toAddPath.push(filePath);
              resolve();
            } else {
              resolve();
            }
          });
        })
      }

      var prevPromise = Promise.resolve();//初始化一个总能被解析的Promise
      toAddOpeningFiles.forEach(function (file) {
        prevPromise = prevPromise.then(function () {//每次迭代时prevPromise发生改变
          return addFilePromise(file);//返回一个新的Promise
        })
      });
      prevPromise.then(function () {
        if (toAddPath.length === 0) {
          hoo.log.info("开服页文件内容无修改");
          resolve();
          return;
        }
        openingClient.cmd(['commit', '-m', title + '----HOO工程化框架自动提交'].concat(toAddPath), function (err) {
          if (err) {
            // hoo.log.error(err);
            return;
          }
          hoo.log.info("开服页文件提交成功");
          resolve();
        });
      });
    })
  });

  return prePromise;
};
