'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

let FAIL_PARAMS_CODE = "0001"
let SUCCESS_CODE = "0000"
let HAVE_DEFAULT_PROJECT = "0002"
let CREATE_FAILED = "0003"
let IS_DEFAULT_PROJECT = "0004"
let DELETE_PROJECT_FAILED = "0005"
// model名称，即表名
exports.model = 'Project';

// 表结构
exports.schema = [{
  name: { type: String, unique: true, required: true },
  is_default: { type: Number, unique: false, required: false },
  urls: [{ type: Schema.Types.ObjectId, required: true, ref: "Url" }]
}, {
  // autoIndex: true,
  versionKey: false
}];

// 静态方法:http://mongoosejs.com/docs/guide.html#statics
exports.statics = {}

// http://mongoosejs.com/docs/guide.html#methods
exports.methods = {
  saveByKey: async function () {
    if (this.name == "") {
      return { code: FAIL_PARAMS_CODE }
    }
    if (this.is_default == 1) {
      let aa = await this.model("Project").find({ is_default: 1 });
      if (aa.length != 0) {
        return { code: HAVE_DEFAULT_PROJECT }
      }
    }
    if (await this.model("Project").find({ name: this.name }) != 0) {
      return { code: CREATE_FAILED }
    }
    return this.save();
  },
  query: async function () {
    return this.model("Project").find()
  },
  delete: async function (_id) {
    console.log(_id)
    let item = await this.model("Project").find({ "_id": _id })
    console.log(item[0])
    if (item[0].is_default == 1) {
      return { code: IS_DEFAULT_PROJECT }
    }
    try {
      await this.model("Project").remove({ "_id": _id });
      return { code: SUCCESS_CODE }
    } catch (error) {
      return { code: DELETE_PROJECT_FAILED }
    }
  },
  update: async function (_id, obj) {
    if (obj.is_default == 1) {
      let default_item = await this.model("Project").find({ is_default: 1 });
      if (default_item._id != _id) {
        return { code: HAVE_DEFAULT_PROJECT }
      }
    }

    return await this.model("Project").update({ "_id": _id }, obj)
  },
  setDefault: async function (_id) {
    let default_item = await this.model("Project").find({ is_default: 1 });
    if (default_item._id != _id) {
     return  await this.model("Project").update({ "_id": default_item._id }, { is_default: 0 }).then(function () {
        this.model("Project").update({ "_id": _id }, { is_default: 1 })
      })
    }
  },
  findById: async function(_id){
    return await this.model("Project").findOne({"_id":_id})
  },
  addUrl: async function () {

  },
  getProjectAndUrls: async function () {
    // let projects = await this.model("Project").find();
    // let url = this.model("Url");
    // console.log(url.schema.methods);
    // let item = []
    // projects.forEach(function(element) {
    //   let u = url.schema.methods.findByProjectId(element["_id"])
    //   console.log(u)
    //   item.push( u )
    // }, this);
    // return item
    await this.model("Project").find().populate({ path: "url", select: "" })
  }
}