/* globals i18n */

import Component from 'ember-component';
import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import { base64EncodeImage } from 'web-client/utilities/html5-loader';
import { TTV_BOXART_404_URL } from 'web-client/utilities/urls/static-cdn';

const ERROR_FILE_TOO_LARGE = i18n('File too large.');
const ERROR_FILE_WRONG_TYPE = i18n('Incompatible format. File must be an image in PNG or JPG format.');
const ERROR_FILE_OTHER = i18n('Upload error');
const FILE_ACCEPTED_TYPES = '^image/(png|jpeg)$';
const FILE_MAX_SIZE = 1000000;

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

  uploadImageTemplate: 'shared/upload-image',
  showRecommendedSize: true,
  communityAvatarImage: true,
  isPositionRelative: false,
  avatarPlaceholder: TTV_BOXART_404_URL,

  avatarImage: computed('communities.communityInfo.avatar_image_url', function() {
    return this.get('communities.communityInfo.avatar_image_url') || TTV_BOXART_404_URL;
  }),

  _checkFile(file) {
    if (!file.type.match(FILE_ACCEPTED_TYPES)) {
      this.set('errorMessage', ERROR_FILE_WRONG_TYPE);
      this.set('isLoading', false);
      return false;
    }
    if (file.size > FILE_MAX_SIZE) {
      this.set('errorMessage', ERROR_FILE_TOO_LARGE);
      this.set('isLoading', false);
      return false;
    }
    return true;
  },

  encodeImage(file) {
    return base64EncodeImage(file).then(result => {
      if (this.isDestroyed) { return; }
      return result;
    }, error => {
      if (this.isDestroyed) { return; }
      if (error.type !== 'error') {
        throw error;
      }
      this.set('errorMessage', ERROR_FILE_OTHER);
    });
  },

  _trackAvatar(oldUrl, newUrl) {
    if (oldUrl === newUrl) {
      return;
    }
    let trackingObject = {
      community_id: this.get('communities.communityInfo._id'),
      community_name: this.get('communities.communityInfo.name'),
      login: this.get('session.userData.login'),
      is_owner: parseInt(this.get('communities.communityInfo.owner_id')) === this.get('session.userData.id'),
      is_subadmin: this.get('session.userData.is_admin'),
      is_admin: this.get('session.userData.is_staff'),
      edit_type: 'avatar',
      old_value: oldUrl,
      new_value: newUrl
    };
    this.get('tracking').trackEvent({
      services: ['spade'],
      event: 'community_edit',
      data: trackingObject
    });
  },

  actions: {
    onFileDrop(file) {
      this.set('isLoading', true);
      this.set('errorMessage', '');

      if (this._checkFile(file)) {
        return this.encodeImage(file).then(result => {
          if (this.isDestroyed) { return; }
          return this.get('communities').uploadCommunityAvatar(result);
        }).then(() => {
          if (this.isDestroyed) { return; }
          let oldUrl = this.get('communities.communityInfo.avatar_image_url');
          let communityName = this.get('communities.communityInfo.name');
          return this.get('communities').getCommunityInfo(communityName).then(result => {
            if (this.isDestroyed) { return; }
            this._trackAvatar(oldUrl, result.avatar_image_url);
            this.set('communities.communityInfo', result);
          });
        }).then(() => {
          if (this.isDestroyed) { return; }
          this.get('closeModal')();
        }, xhr => {
          if (this.isDestroyed) { return; }
          if (xhr.target && xhr.target.status & xhr.target.status === 413) {
            this.set('errorMessage', ERROR_FILE_TOO_LARGE);
          } else {
            this.set('errorMessage', ERROR_FILE_OTHER);
          }
        }).finally(() => {
          if (this.isDestroyed) { return; }
          this.set('isLoading', false);
        });
      }
    },

    removeAvatar() {
      this.get('communities').deleteCommunityAvatar().then(() => {
        if (this.isDestroyed) { return; }
        let oldUrl = this.get('communities.communityInfo.avatar_image_url');
        this._trackAvatar(oldUrl, '');
        this.set('communities.communityInfo.avatar_image_url', '');
      });
    }
  }
});
