/**
 * Created by jimiz on 2017/5/12.
 */
var mongoose = require("mongoose");
var db = require("../db/unit_price_file_db");
var Schema = mongoose.Schema;
var deleteSchema = require('../../../public/models/delete_schema');
var consts = require('../../main/models/project_consts');
var projectConsts = consts.projectConst;
var commonConsts = consts.commonConst;
var GLJList = require('./glj_list');

var unitPriceFileSchema = new Schema({
    ID: Number,
    name: String,
    version: Number,
    projects: Array,
    deleteInfo: deleteSchema
});

var unitPriceFile = db.model("unitPriceFile", unitPriceFileSchema, "unitPriceFile");

var unitPriceFileDAO = function(){};

unitPriceFileDAO.prototype.getData = function(fileID, callback){
    unitPriceFile.find({'$or': [{fileID: fileID, deleteInfo: null}, {fileID: fileID, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id', function(err, datas){
        if (!err) {
            callback(0, projectConsts.UNITPRICEFILE, datas);
        } else {
            callback(1, '', null);
        }
    });
};

unitPriceFileDAO.prototype.save = function(fileId, datas, callback){
    function changed(err, changedDatas){
        sync(fileId, changedDatas, callback);
    }


    GLJList.save(fileID, datas, changed);
};

unitPriceFileDAO.prototype.sync = function(fileID, datas, callback){
    unitPriceFile.find({'$or': [{ID: fileID, deleteInfo: null}, {ID: fileID, 'deleteInfo.deleted': {$in: [null, false]}}]}, '-_id', function(err, datas){
        if (!err) {
            datas[0].projects

            callback(0, projectConsts.UNITPRICEFILE, datas);
        } else {
            callback(1, '', null);
        }
    });
};

unitPriceFileDAO.prototype.add = function(fileID, count, callback){
    GLJList.add(fileID, count, callback);
};

unitPriceFileDAO.prototype.newFile = function(data, callback){

};

unitPriceFileDAO.prototype.useFile = function(fileID, projectID, callback){

};

unitPriceFileDAO.prototype.unuseFile = function(fileID, projectID, callback){

};

module.exports = new unitPriceFileDAO();