'use strict';
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// model名称，即表名
exports.model = 'DeviceProjectRoute';

// 表结构
exports.schema = [{
  name: { type: String, unique: true, required: true },
  ipv4: { type: String, unique: true, required: true },
  ipv6: { type: String, unique: true, required: true },
  projects: {type: Schema.Types.ObjectId, ref: "Project"}
}, {
  // 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.projects == undefined){
      this.projects = await this.model("Project").find({is_default:1})[0]
    }
    let aa = await this.model("Url").find({
      ipv4: this.ipv4,
      ipv6: this.ipv6,
      projects: this.projects
    });
    if(aa.length != 0){
      return false
    }

    if(this.ipv6 == undefined || this.ipv6 == ""){
      this.ipv6 = "ffff"
    }
    return this.save();
  },
  add: async function() {
    return this.save();
  } 
}
