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

const Card = require('./card');
const ContactPerson = require('../core/contact-person');

class InspectCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'INSPECT';
    this.details = {
      partyType: null,
      partyId: null,
      partyName: null,
      memberId: null,
      memberName: null,
      buildingId: null,
      buildingName: null,
      floorId: null,
      floorName: null,
      people: [],
    };

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

  fillObject(details) {
    this.details.partyType = details.partyType || null;
    this.details.partyId = details.partyId ? new ObjectId(details.partyId) : null;
    this.details.partyName = details.partyName || null;
    this.details.memberId = details.memberId ? new ObjectId(details.memberId) : null;
    this.details.memberName = details.memberName || null;
    this.details.buildingId = details.buildingId || null;
    this.details.buildingName = details.buildingName || null;
    this.details.floorId = details.floorId || null;
    this.details.floorName = details.floorName || null;
    this.details.people = details.people ? details.people.map((item) => new ContactPerson(item)) : [];
  }

  getLabel() {
    const { partyType, partyId, partyName, memberId, memberName } = JSON.parse(JSON.stringify(this.details));
    return { partyType, partyId, partyName, memberId, memberName };
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'inspect-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              partyType: { type: ['string', 'null'] },
              partyId: { type: ['object', 'null'] },
              partyName: { type: ['string', 'null'] },
              memberId: { type: ['object', 'null'] },
              memberName: { type: ['string', 'null'] },
              buildingId: { type: ['string', 'null'] },
              floorId: { type: ['string', 'null'] },
              buildingName: { type: ['string', 'null'] },
              floorName: { type: ['string', 'null'] },
              people: { type: 'array', item: { $ref: 'contact-person.schema.json' } },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());
tv4.addSchema(ContactPerson.schema());

module.exports = InspectCard;
