/*
 * 提交源码目录下的文件到svn
 * */
var Client = require('svn-spawn');
var path = require('path');
var settings = require('../conf/settings');
var hoo = require('../');
var _ = require('./util');
var jsdom = require('jsdom');
module.exports = function (root, destDir, files, project_title) {
  destDir = destDir || settings.sourceDir;
  var rootClient = new Client({
    cwd: process.cwd()
  });

  var superClient = new Client({
    cwd: path.join(process.cwd(), destDir, root, '../')
  });

  var client = new Client({
    cwd: path.join(process.cwd(), destDir, root)
  });

  var gamekeyNotCommited = false;
  var uniqueIdNotCommitted = false;

  var deployPath = path.join(destDir, root).replace(/\\/g, '/');
  var deployPath_super = path.join(deployPath, '../').replace(/\\/g, '/');
  var prePromise = Promise.resolve();
  if (!project_title) {
    prePromise = prePromise.then(function () {
      return new Promise(function (resolve) {
        jsdom.env(
          path.join(process.cwd(), destDir, root, 'index.html'),
          function (err, window) {
            project_title = window.document.title;
            resolve();
          }
        )
      });
    })
  }

  //添加或删除gamekey目录，并提交到svn
  var addSuperPromise = prePromise.then(function () {
    return new Promise(function (resolve) {
      superClient.getStatus(function (err, data) {
        if (err) {
          hoo.log.debug(err);
          return;
        }
        if (data.length === 0) {
          hoo.log.info(deployPath_super + '目录下内容无修改');
          return;
        }
        var item1 = data[0].$;
        if (item1.path !== '.') {
          resolve();
          return;
        }
        var status = data[0]['wc-status'].$.item;
        // add
        if (['none', 'unversioned'].indexOf(status) !== -1) {
          gamekeyNotCommited = true;
          rootClient.add([deployPath_super, '--non-recursive'], function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            resolve();
          })
        }
        // delete
        else if (['missing'].indexOf(status) !== -1) {
          client.del(deployPath_super, function (err) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            rootClient.commit([project_title + ':删除' + deployPath_super + '空目录' + '----HOO工程化框架自动提交', deployPath_super], function (err, data) {
              if (err) {
                hoo.log.debug(err);
                return;
              }
            });
          });
        } else if (['added'].indexOf(status) !== -1) {
          rootClient.commit([project_title + ':创建' + deployPath_super + '空目录' + '----HOO工程化框架自动提交', deployPath_super], function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            hoo.log.info('目录:' + deployPath_super + '-Commit To SVN');
            resolve();
          });
        } else if (['modified'].indexOf(status) !== -1) {
          resolve();
        } else {
          resolve();
        }
      });
    });
  });

  //添加或删除gamekey目录下的某个活动目录
  var addPathPromise = addSuperPromise.then(function () {
    return new Promise(function (resolve) {
      client.getStatus(function (err, data) {
        if (err) {
          hoo.log.debug(err);
          return;
        }
        if (data.length === 0) {
          hoo.log.info(deployPath + '目录下内容无修改.');
          return;
        }
        var item1 = data[0].$;
        if (item1.path !== '.') {
          resolve();
          return;
        }
        var status = data[0]['wc-status'].$.item;
        // add
        if (['none', 'unversioned'].indexOf(status) !== -1) {

          uniqueIdNotCommitted = true;
          rootClient.add([deployPath, '--non-recursive'], function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            resolve();
          })
        }
        // delete
        else if (['missing'].indexOf(status) !== -1) {
          rootClient.del(deployPath, function (err) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            rootClient.commit([project_title + ':删除' + deployPath + '空目录' + '----HOO工程化框架自动提交', deployPath], function (err, data) {
              if (err) {
                hoo.log.debug(err);
                return;
              }
            })
          });
        }
        // added
        else if (['added'].indexOf(status) !== -1) {

          rootClient.commit([project_title + ':创建' + deployPath + '空目录' + '----HOO工程化框架自动提交', deployPath], function (err, data) {
            if (err) {
              hoo.log.debug(err);
              return;
            }
            hoo.log.info('目录:' + deployPath + '-Commit To SVN');
            resolve();
          });
        }
        //modified
        else if (['modified'].indexOf(status) !== -1) {
          //underVersioned?
          resolve();
        } else {
          resolve();
        }
      });
    });

  });

  //更新专题活动目录代码
  var updateFilesPromise = addPathPromise.then(function () {
    hoo.log.info("开始更新目录" + deployPath + "...\n");
    return new Promise(function (resolve) {
      client.update(function (err) {
        if (err) {
          hoo.log.debug(err);
          return;
        }
        hoo.log.info('目录:' + deployPath + '下文件更新成功');
        resolve();
      });
    });
  });

  //提交专题活动目录代码
  var addFilesPromise = updateFilesPromise.then(function () {
    return new Promise(function (resolve) {
      if (files && files.length > 0) {

      } else {
        files = _.getAllFiles(deployPath, settings.svnIgnore.split(','));
      }

      function addFilePromise(file) {
        return new Promise(function (resolve) {
          client.getStatus(path.relative(deployPath, 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(deployPath, file.path)) {
              resolve();
              return;
            }
            var status = data[0]['wc-status'].$.item;
            // add
            if (['none', 'unversioned'].indexOf(status) !== -1) {
              client.add([path.relative(deployPath, file.path), '--non-recursive', '--parents'], function (err, data) {
                if (err) {
                  hoo.log.debug(err);
                  /*if (file.dir) {
                   resolve();
                   }*/
                  return;
                }
                resolve();
              })
            }
            // delete
            else if (['missing'].indexOf(status) !== -1) {
              client.del(path.relative(deployPath, file.path), function (err) {

              });
            } else if (['modified'].indexOf(status) !== -1) {
              resolve();
            } else if (['added'].indexOf(status) !== -1) {
              resolve();
            }  else if (['replaced'].indexOf(status) !== -1) {
              resolve();
            } else {
              hoo.log.error("未知错误");
            }
          });
        })
      }

      var prevPromise = Promise.resolve();//初始化一个总能被解析的Promise
      files.forEach(function (file) {
        prevPromise = prevPromise.then(function () {//每次迭代时prevPromise发生改变
          return addFilePromise(file);//返回一个新的Promise
        })
      });
      prevPromise.then(function () {
        hoo.log.info('目录:' + deployPath + '下所有文件-Added To SVN');
        resolve();
      });
    })
  });

  return addFilesPromise.then(function () {
    return new Promise(function (resolve) {
      if(gamekeyNotCommited){
        console.log(111);
        rootClient.commit([project_title + '----HOO工程化框架自动提交', deployPath_super], function (err, data) {
          if (err) {
            hoo.log.debug(err);
            return;
          }
          resolve();
        });
      }else if(uniqueIdNotCommitted){
        console.log(222);
        rootClient.commit([project_title + '----HOO工程化框架自动提交', deployPath], function (err, data) {
          if (err) {
            hoo.log.debug(err);
            return;
          }
          resolve();
        })
      }else{
        console.log(333);
        client.commit(project_title + '----HOO工程化框架自动提交', function (err, data) {
          if (err) {
            hoo.log.debug(err);
            return;
          }
          hoo.log.info('成功提交至svn库(HOO工程化框架自动提交)');
          resolve();
        });
      }
    });
  });
};
