const ObjectId = require('bson').ObjectID;
const clone = require('clone');
const tv4 = require('tv4');

const CardOptionValue = require('./card-option-value');

class CardOption {
  constructor(opt) {
    this._id = null;
    this.campusCode = null;
    this.isInternal = false;
    this.name = null;
    this.options = [];
    this.tags = [];

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

  fillObject(opt) {
    this._id = new ObjectId(opt._id);
    this.campusCode = opt.campusCode;
    this.isInternal = opt.isInternal || false;
    this.name = opt.name;
    this.tags = Array.isArray(opt.tags) ? [...opt.tags] : [];

    if (opt.options) {
      opt.options.forEach((item) => this.options.push(new CardOptionValue(item)));
    }
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'card-option.schema.json',
      type: 'object',
      additionalProperties: false,
      properties: {
        _id: { type: 'object' },
        campusCode: { type: 'string' },
        isInternal: { type: 'boolean' },
        name: { type: 'string' },
        options: { type: 'array', items: { $ref: 'card-option-value.schema.json' } },
        tags: { type: 'array', item: { type: 'string' } },
      },
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(CardOptionValue.schema());
module.exports = CardOption;
