import Service from './service';
import EventsMixin from './mixin/events';

const ContentModel = window.require('core/models/content');

export default class ContentServiceWithEvents extends EventsMixin(Service) {
  constructor(user) {
    super();
    this.userIsPremium = user.premium;
    this.events = ['change', 'error'];
    ContentModel.on('change', this._broadcast.change);
  }

  getItemsByService(service) {
    return ContentModel.select(
      item => (item.metadata ? item.metadata.service === service : false)
    );
  }

  maxContentReached(composition) {
    const meta = composition.contentMeta();
    const limit = this.userIsPremium
      ? meta.options.max
      : meta.options.free_user_limit;
    return composition.maxContentReached(limit);
  }

  toggleItem(composition, service, id, value, extra = {}, metadata = {}) {
    const item = this.getItemsByService(service)
      .filter(item => item.metadata.id === id)
      .pop();

    if (item) {
      item.destroy();
    } else {
      this.addItem(
        composition,
        value,
        extra,
        Object.assign({}, metadata, { id, service })
      );
    }
  }

  addItem(composition, value, extra, metadata) {
    // TODO require metadata.id
    // TODO require metadata.service
    const meta = composition.contentMeta();

    if (this.maxContentReached(composition) && meta.options.max > 1) {
      this._broadcast.error(this.userIsPremium ? 'max' : 'maxFree');
      throw new Error('Cannot add more than max items');
    }

    if (this.maxContentReached(composition) && meta.options.max === 1) {
      ContentModel.select(
        item => item.composition_id === composition.id
      ).forEach(item => item.destroy());
    }

    const item = new ContentModel(
      Object.assign({}, extra, {
        composition_id: composition.id,
        metadata,
        [meta.options.mainAttribute]: value,
      })
    );
    item.save();
  }
}
