const { ObjectId } = require('bson');
const tv4 = require('tv4');

const EDGE_ROLE = require('../../constant/relationship/edge-role.constant');

class Edge {
  constructor(opt) {
    this._id = null;
    this.target = null;
    this.source = null;
    this.role = null;
    this.isActive = null;
    this.primary = null;
    this.startDate = null;
    this.endDate = null;
    this.events = null;

    if (opt) {
      this.fillObject(opt);
    }
  }

  fillObject(opt) {
    this._id = new ObjectId(opt._id);
    this.target = opt.target;
    this.source = opt.source;
    this.role = opt.role;
    this.startDate = opt.startDate ? new Date(opt.startDate) : new Date();
    this.endDate = opt.endDate ? new Date(opt.endDate) : null;
    this.events = (opt.events || []).map((e) => ({ event: e.event, date: new Date(e.date) }));

    this.isActive = !this.endDate || this.endDate > new Date();
    this.primary = !!opt.primary;
  }

  validate() {
    return tv4.validateMultiple(this, Edge.schema());
  }

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'edge.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        _id: { type: 'object' },
        target: { type: 'string' },
        source: { type: 'string' },
        role: { enum: Object.keys(EDGE_ROLE) },
        isActive: { type: 'boolean' },
        primary: { type: 'boolean' },
        startDate: { type: 'object' },
        endDate: { type: ['object', 'null'] },
        events: { type: 'array', items: { type: 'object' } },
      },
      required: Object.keys(new Edge()),
    };
  }
}

module.exports = Edge;
