/* globals i18n */

import Component from 'ember-component';
import RSVP from 'rsvp';
import $ from 'jquery';
import { CancellationError } from 'web-client/utilities/error';
import injectService from 'ember-service/inject';

export default Component.extend({
  tagName: 'span',
  layoutName: 'components/edit-modal',

  notify: injectService(),

  click() {
    this.sendAction('openInModal', this.get('template'), this);
  },

  isValid() {
    return new RSVP.Promise((resolve) => {
      if (!this.validateRequiredFields($('.twitch_subwindow form input'))) {
        return resolve({isValid: false, msg: 'Field is required'});
      }
      resolve({isValid: true});
    });
  },

  // Return true if all required fields are set and have values
  validateRequiredFields(inputs) {
    return !(inputs.toArray().find((el) => {
      let $el = $(el);
      return $el.prop('required') && !$el.val().trim();
    }));
  },

  save() {
    let data = this.serializeObject($('.twitch_subwindow form'));
    let notify = this.get('notify');

    this.get('content').save(data).then(() => {
      if (this.isDestroyed) { return; }
      this.sendAction('closeModal', this);
    }, (err) => {
      if (this.isDestroyed) { return; }
      try {
        notify.error(i18n(JSON.parse(err.responseText).message));
      } catch (e) {
        notify.error(i18n('There was a problem editing status'));
        return RSVP.reject(err);
      }
    });
  },

  serializeObject(form) {
    let o = {};
    let a = form.serializeArray();
    a.forEach((object) => {
      if (o[object.name]) {
        if (!o[form.name].push) {
          o[object.name] = [o[object.name]];
        }
        o[object.name].push(object.value || '');
      } else {
        o[object.name] = object.value || '';
      }
    });
    return o;
  },

  actions: {
    update() {
      let notify = this.get('notify');

      this.isValid().then(({isValid, msg}) => {
        if (this.isDestroyed) { return; }
        if (!isValid) {
          notify.error(i18n(msg));
          return;
        }
        this.save();
      }, (err) => {
        if (this.isDestroyed) { return; }
        if (err instanceof CancellationError) { return; }
        notify.error(i18n('There was a problem editing status'));
        throw err;
      });
    },

    closeModal() {
      this.sendAction('closeModal', this);
    }
  }
});
