var util = require('util');
var fs = require('fs') ;
var path = require('path');
var Service = require('Service');
var utils = require('utils');
var AttachDao = require('../../dao/app_attach');

var CopyAttach = function() {
  Service.call(this);
  this.index = 0;
};

util.inherits(CopyAttach, Service);

module.exports = CopyAttach;

CopyAttach.prototype.process =  function(req, res, cb) {
  if(!req.files || req.files.length===0) {
    this.onLogicError(1, '请提供文件信息！');
    return;
  }
  
  this.daoAttach = new AttachDao(this);
  this.copyFile(req, res);
};

CopyAttach.prototype.copyFile =  function(req, res, cb) {
  if(this.index>=req.files.length) {
    if(cb){
      cb(req, res);
      return;
    }
    this.end(res);
    return;
  }
  var self = this;
  var attach = req.files[this.index];
  if(attach.srcPath.indexOf('/files/')==0) attach.srcPath = attach.srcPath.substring(7);
  attach.srcPath = path.join(server.attachSavePath, attach.srcPath);
  attach.desPath = '/'+req.session.orgCode+'/';
  if(!fs.existsSync(path.join(server.attachSavePath, attach.desPath))) 
    fs.mkdirSync(path.join(server.attachSavePath, attach.desPath));
  attach.desPath += attach.appCode+'/';
  if(!fs.existsSync(path.join(server.attachSavePath, attach.desPath))) 
    fs.mkdirSync(path.join(server.attachSavePath, attach.desPath));
  attach.desPath += utils.formatDate(new Date(), 'yyyy_MM')+'/';
  if(!fs.existsSync(path.join(server.attachSavePath, attach.desPath))) 
    fs.mkdirSync(path.join(server.attachSavePath, attach.desPath));
  attach.desPath += attach.code+'.file';
  var rs = fs.createReadStream(attach.srcPath);
  var ws = fs.createWriteStream(path.join(server.attachSavePath, attach.desPath));
  ws.on('finish', function() {
    var obj = {};
    obj.code = attach.code;
    obj.name = attach.name;
    obj.size = attach.size;
    obj.type = path.extname(attach.name);
    obj.app_code = attach.appCode;
    if(attach.appDataId) obj.app_data_id = attach.appDataId;
    obj.uploader_id = req.session.userId;
    obj.uploader_name = req.session.userName;
    obj.upload_time = new Date();
    obj.save_path = attach.desPath.replace(/\\/g,'/');
    obj.org_id = req.session.orgId;
    self.daoAttach.create(obj, function(ret) {
      self.index++;
      self.copyFile(req, res, cb);
    });
  });
  rs.pipe(ws);
};