/* globals Twitch, _ */

import Component from 'ember-component';
import computed from 'ember-computed';
import on from 'ember-evented/on';
import CommunityGamesMixin from 'web-client/mixins/community-games';
import $ from 'jquery';
import injectService from 'ember-service/inject';

export const IMAGE_TYPE_ERROR = "Image format must be jpg, jpeg, or png";
export const ACCEPTED_FILE_TYPES = ["image/png", "image/jpeg"];
const CUSTOM_THUMBNAIL = 'custom';
const MAX_SIZE = 2000000;
const FILE_SIZE_ERROR = "Your file exceeds the max size of 2MB";
const TRACKING_EVENT_NAME = "vod_edit";

let contentSaveDone = false;
let imageSaveDone = false;
let oldFormObject = {};

export default Component.extend(CommunityGamesMixin, {
  tracking: injectService(),

  contentTitle: computed.alias('content.title'),
  contentGame: computed.alias('content.game'),

  actions: {
    selectThumbnail: function (thumbnailIndex) {
      this.set('thumbnailIndex', thumbnailIndex);
      this.resetUpload();
    },

    deleteOldCustomThumbnail: function () {
      this.set('deleteCustomThumbnail', true);
      let newThumbnailIndex = this.get('customThumbnail.index') === 0 ? 1 : 0;
      this.set('thumbnailIndex', newThumbnailIndex);
    },

    resetUpload: function () {
      this.resetUpload();
    },

    update: function () {
      let data = this.serializeObject($(".twitch_subwindow form"));
      let imageData = this.get('content.imageData');
      this.set('currentlySaving', true);

      this.trackData(data);

      if (imageData) {
        if (this.meetsImageRequirements()) {
          this.submitImageData();
        }
      } else {
        data.thumbnail_index = this.get('thumbnailIndex');
        data.delete_custom_thumbnail = !!this.get('deleteCustomThumbnail');
      }

      if (this.get('currentlySaving')) {
        this.saveGameData(data, imageData);
      }
    },

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

  updateThumbnailValues: function (thumbnails) {
    if (!Array.isArray(thumbnails)) {
      return;
    }
    this.set('content.thumbnails', thumbnails);
    this.set('content.preview', thumbnails[0].url);
  },

  serializeObject: function (form) {
    let o = {};
    let a = form.serializeArray();
    _.each(a, function (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;
  },

  saveGameData: function (data, imageData) {
    this.get('content').save(data).then((response) => {
      if (response.thumbnails) {
        this.updateThumbnailValues(response.thumbnails);
      }
      if (!imageData || imageSaveDone) {
        this.sendAction('closeModal', this);
      }
      contentSaveDone = true;
    }, (response) => {
      try {
        this.set('errorMessage', JSON.parse(response.responseText).message);
      } catch (e) {
        this.set('errorMessage', "There was a problem editing status");
      }
      this.set('currentlySaving', undefined);
    });
  },

  meetsImageRequirements: function () {
    let image = this.get('content.file');
    if (!image || typeof(image) !== "object") {
      imageSaveDone = true;
      return false;
    }

    if (image.size > MAX_SIZE) {
      this.set('errorMessage', FILE_SIZE_ERROR);
      this.set('currentlySaving', undefined);
      return false;
    }

    if (ACCEPTED_FILE_TYPES.indexOf(image.type) < 0) {
      this.set('errorMessage', IMAGE_TYPE_ERROR);
      this.set('currentlySaving', undefined);
      return false;
    }

    return true;
  },

  submitImageData: function () {
    let imageData = this.get('content.imageData');
    imageData.submit().done((response) => {
      if (response.thumbnails) {
        this.updateThumbnailValues(response.thumbnails);
        this.set('content.imageData', undefined);
      }

      if (contentSaveDone) {
        this.sendAction('closeModal', this);
      }
      imageSaveDone = true;
    })
    .fail((response) => {
      try {
        this.set('errorMessage', JSON.parse(response.responseText).message);
      } catch (e) {
        this.set('errorMessage', "There was a problem saving the image.");
      }
      this.set('currentlySaving', undefined);
    });
  },

  trackData(newFormObject) {
    let trackingObj = {
      login: Twitch.user.login(),
      channel: this.get('content.channel.name'),
      vod_id: this.get('content.id').substring(1),
      vod_type: this.get('content.broadcast_type'),
      device_id: Twitch.idsForMixpanel.getOrCreateUniqueId(),
      deleted_thumbnail: !!this.get('deleteCustomThumbnail'),
      uploaded_thumbnail: !!this.get('content.imageData'),
      changed_thumbnail: !!this.get('content.imageData') ||
        this.get('thumbnailIndex') !== 0 ||
        !!this.get('deleteCustomThumbnail') && this.get('thumbnailIndex') === 0,
      changed_title: newFormObject.title !== oldFormObject.title,
      changed_description: newFormObject.description !== oldFormObject.description,
      changed_game: newFormObject.game !== oldFormObject.game,
      changed_tags: newFormObject.tag_list !== oldFormObject.tag_list
    };


    this.get('tracking').trackEvent({
      event: TRACKING_EVENT_NAME,
      data: trackingObj
    });
  },

  resetUpload: function () {
    this.set('content.file', undefined);
    this.set('content.imageData', undefined);
    $('.modal__cropper').remove();
  },

  setUploadedThumbnailIndex: on('init', function () {
    let thumbnails = this.get('content.thumbnails') || [];
    for (let i = 0; i < thumbnails.length; i++) {
      if (thumbnails[i].type === CUSTOM_THUMBNAIL) {
        this.set('customThumbnail', {index: i, url: thumbnails[i].url});
      }
    }
  }),

  setupVariables: on('init', function () {
    contentSaveDone = false;
    imageSaveDone = false;
    this.set('thumbnailIndex', 0);
    this.resetUpload();
  }),

  setOldFormObject: on('didInsertElement', function () {
    // We use the current form object to diff it with the submitted one.
    oldFormObject = this.serializeObject($(".twitch_subwindow form"));
  }),

  thumbnailUploadHref: computed('content.id', function () {
    let vodId = this.get('content.id').substring(1);
    return `${Twitch.api.config.baseUrl}/api/vods/${vodId}/upload_thumbnail`;
  }),

  showUploadedSection: computed('customThumbnail', 'deleteCustomThumbnail', function () {
    return this.get('customThumbnail') && !this.get('deleteCustomThumbnail');
  }),

  selectedThumbnailSrc: computed('thumbnailIndex', function () {
    return this.get(`content.thumbnails.large.${this.get('thumbnailIndex')}.url`);
  })
});
