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

const Card = require('./card');
const TableItemSchema = require('./table-item-schema');

class TableCard extends Card {
  constructor(opt) {
    super(opt);
    this.type = 'TABLE';
    this.details = {
      description: null,
      schema: [],
      items: [],
      canAddRows: true,
      layout: 'TABLE',
    };

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

  fillObject(details) {
    this.details.description = details.description || null;
    this.details.items = details.items || [];
    this.details.canAddRows = 'canAddRows' in details ? details.canAddRows : true;
    this.details.layout = details.layout || 'TABLE';

    if (details.schema) {
      details.schema.forEach((i) => {
        const schema = new TableItemSchema(i);
        this.details.schema.push(schema);

        if (schema.type === 'DATE') {
          this.details.items.forEach((item) => {
            if (item[schema.key]) {
              item[schema.key] = new Date(item[schema.key]); // eslint-disable-line
            }
          });
        }
      });
    }
  }

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

  static schema() {
    return {
      $schema: 'http://json-schema.org/draft-04/schema#',
      id: 'table-card.schema.json',
      type: 'object',
      allOf: [
        { $ref: 'card.schema.json' },
        {
          properties: {
            details: {
              description: { type: ['string', 'null'] },
              schema: { type: 'array', items: { $ref: 'table-item-schema.schema.json' } },
              items: { type: 'array', items: { type: 'object' } },
              canAddRows: { type: 'boolean' },
              layout: { type: 'string', enum: ['TABLE', 'VERTICAL'] },
            },
          },
        },
      ],
      required: Object.keys(this),
    };
  }
}

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

module.exports = TableCard;
