/* globals Twitch */

import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import ChannelModel from 'web-client/models/deprecated-channel';
import StoreModel from 'web-client/models/store';
import logApiFailure from 'web-client/utilities/log-api-failure';

let TicketModel = StoreModel.defineModel({
  relationships: {
    'product.partner': function () {
      let partnerChannel = ChannelModel.find({id: this.get('product.partner_login')});
      partnerChannel.load();
      return partnerChannel;
    }
  },

  deserialize(data) {
    data.product.emoticons.forEach(function (emoticon) {
      emoticon.active = emoticon.state === "active";
    });
    return data;
  }
});

TicketModel.defineCollection('user', {
  api: injectService(),

  limit: 20,

  request() {
    if (!Twitch.user.isLoggedIn()) {
      this.set('isLoaded', true);
      this.set('isLoading', false);
      return;
    }

    let api = this.get('api');
    let channel = this.get('channel');

    if (channel) {
      return api.request('get', `/api/users/:login/tickets?channel=${channel}`);
    }

    let data = {
      limit: this.limit,
      offset: this.get('content.length'),
      unended: true
    };

    return api.request('get', '/api/users/:login/tickets', data);
  },

  afterSuccess(response) {
    this.set('isLoaded', true);
    this.setContent(response.tickets);
  },

  afterFail() {
    this.set('isLoaded', true);
    logApiFailure('user tickets');
  },

  isSubscribed: computed.gt('content.length', 0)
});

export default TicketModel;
