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

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

class ConditionCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'CONDITION';
    this.details = {
      cards: [],
      conditions: {},
      description: null,
      header: '',
      title: null,
      value: null,
    };

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

  getOptions() {
    return Object.keys(this.details.conditions);
  }

  setCondition(value) {
    this.fillCards(this.details.conditions[value]);
  }

  fillObject(details) {
    this.details.conditions = details.conditions || {};
    this.details.description = details.description || null;
    this.details.header = details.header || '';
    this.details.title = details.title || null;
    this.details.value = details.value || null;

    this.fillCards(details.cards);
    this.isValid = !!this.details.value && !this.details.cards.some((c) => !c.isValid);
  }

  fillCards(cards) {
    if (Array.isArray(cards)) {
      const { createCardFactory } = require('../../helper/card-factory'); // eslint-disable-line
      this.details.cards = cards.map((card) => createCardFactory(card.type, { ...card }));
    }
  }

  calculateCounts(count) {
    const result = { ...count };
    this.details.cards.forEach((card) => {
      if (card.details.countLabel) {
        result[card.details.countLabel] = (result[card.details.countLabel] || 0) + card.details.count;
      }
    });
    return result;
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'condition-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              conditions: { type: 'object' },
              cards: { type: 'array', items: { type: 'object' } },
              description: { type: ['string', 'null'] },
              header: { type: 'string' },
              title: { type: ['string', 'null'] },
              value: { type: ['string', 'null'] },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

tv4.addSchema(Card.schema());

module.exports = ConditionCard;
