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

const FileReference = require('./file-reference');

class Card {
  constructor(opt) {
    this.id = null;
    this.type = null;
    this.attachments = [];
    this.comment = null;
    this.isRequired = false;
    this.isMovable = true;
    this.isEditable = true;
    this.allowAttachments = true;
    this.allowComment = false;
    this.label = {};
    this.isValid = true;

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

  fillBaseObject(opt) {
    this.id = new ObjectId(opt.id);
    this.type = opt.type || null;
    const checkBoolean = (property, fallback) => (typeof property === 'boolean' ? property : fallback);
    this.allowAttachments = checkBoolean(opt.allowAttachments, this.allowAttachments);
    this.allowComment = checkBoolean(opt.allowComment, this.allowComment);
    this.isEditable = checkBoolean(opt.isEditable, this.isEditable);
    this.isMovable = checkBoolean(opt.isMovable, this.isMovable);
    this.isRequired = checkBoolean(opt.isRequired, this.isRequired);

    if (opt.attachments) {
      opt.attachments.forEach((attachment) => this.attachments.push(new FileReference(attachment)));
    }
    this.comment = opt.comment !== null && opt.comment !== undefined ? opt.comment : this.comment;
    this.label = opt.label || {};
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'card.schema.json',
      type: 'object',
      properties: {
        id: { type: ['object', 'null'] },
        type: { type: 'string' },
        attachments: { type: 'array', items: { $ref: 'file-reference.schema.json' } },
        comment: { type: ['string', 'null'] },
        isRequired: { type: 'boolean' },
        isMovable: { type: 'boolean' },
        isEditable: { type: 'boolean' },
        allowAttachments: { type: 'boolean' },
        allowComment: { type: 'boolean' },
        label: { type: 'object' },
        isValid: { type: 'boolean' },
      },
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(FileReference.schema());

module.exports = Card;
