const clone = require('clone');
const tv4 = require('tv4');

const PersonReference = require('../core/person-reference');

const Card = require('./card');

class AcknowledgmentCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'ACKNOWLEDGEMENT';
    this.details = {
      acknowledgeLabel: 'Acknowledged by:',
      prompt: '',
      signatures: [],
      requiredSignatures: [],
    };

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

  fillObject(details) {
    this.details.acknowledgeLabel = details.acknowledgeLabel || this.details.acknowledgeLabel;
    this.details.prompt = details.prompt || '';
    this.details.signatures = (details.signatures || []).map((signature) => ({
      person: new PersonReference(signature.person),
      date: signature.date ? new Date(signature.date) : new Date(),
    }));
    if (Array.isArray(details.requiredSignatures)) {
      this.details.requiredSignatures = details.requiredSignatures.map(({ person }) => ({
        person: new PersonReference(person),
        hasSigned: !!this.details.signatures.some((signature) => signature.person.userId === person.userId),
      }));
    }
    this.isValid = !!(this.details.requiredSignatures.length && this.details.signatures.length);
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'acknowledgement-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              acknowledgeLabel: { type: 'string' },
              prompt: { type: 'string' },
              requiredSignatures: {
                type: 'array',
                items: {
                  person: { $ref: 'person-reference.schema.json' },
                  hasSigned: { type: 'boolean' },
                },
              },
              signatures: {
                type: 'array',
                items: {
                  person: { $ref: 'person-reference.schema.json' },
                  date: { type: 'object' },
                },
              },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

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

module.exports = AcknowledgmentCard;
