/* globals i18n */
import injectService from 'ember-service/inject';
import Service from 'ember-service';
import RSVP from 'rsvp';
import $ from 'jquery';
import computed from 'ember-computed';
import run from 'ember-runloop';
import { JTV_USER_PICTURES_404_USER_70X70_URL } from 'web-client/utilities/urls/static-cdn';
import { uploadLegacyData } from 'web-client/utilities/upload-form-data';

const ACCEPTED_FILE_TYPES = /^image\/(gif|jpe?g|png)$/i;

export default Service.extend({
  session: injectService(),
  store: injectService(),
  ajax: injectService(),
  notify: injectService(),
  api: injectService(),

  isLoggedIn: computed.readOnly('session.isAuthenticated'),
  userData: computed.readOnly('session.userData'),
  userModel: computed.readOnly('session.userModel'),

  verifyEmail() {
    let email = this.get('session.userModel.email');
    return new RSVP.Promise((resolve, reject) => {
      $.post('/user/send_verification', {
        email: email
      }).done(() => {
        run(null, resolve);
      }).fail((jqXHR) => {
        run(null, reject, jqXHR);
      });
    });
  },

  /*
   * Both update the user data on the server and upload a new profile image.
   *
   * TODO: Fixme to fully use user ember-data, use users-service API for updating user settings
   *       when the API exists
   */
  updateProfileSettings(file) {
    let user = this.get('session.userModel');
    let store = this.get('store');
    let feedUser = store.peekRecord('feed-user', user.get('_id'));
    let api = this.get('api');
    let login = user.get('id');

    let userData = {
      'user[email]': user.get('email'),
      'user[description]': (user.get('bio') || ''),
      'user[delete_profile_image]': this.removeProfilePicture,
      'section': 'profile'
    };

    if (file) {
      userData['user[profile_image]'] = file;
    }

    if (this._checkBio(user.get('bio')) && this._checkFile(file)) {
      // Handle updating profile displayName first before updating rest of profile due to lack of API
      // TODO:  Simplify this perhaps
      return api.request('put', `/kraken/users/${login}`, { displayname: user.updatedDisplayName })
        .then(() => {
          if (this.isDestroyed) { return; }
          user.setProperties({
            displayName: user.updatedDisplayName
          });
          user.save();

          return uploadLegacyData('/settings', userData).then(() => {
            if (this.get('removeProfilePicture')) {
              user.setProperties({logo: JTV_USER_PICTURES_404_USER_70X70_URL});
              if (feedUser) {
                feedUser.setProperties({profileImage: JTV_USER_PICTURES_404_USER_70X70_URL});
              }
            }

            user.reload();
            if (feedUser) {
              feedUser.reload();
            }
            this.set('removeProfilePicture', false);
          });
        });
    }
  },

  _checkFile(file) {
    if (!file) {
      return true;
    }

    let notify = this.get('notify');
    if (!ACCEPTED_FILE_TYPES.test(file.type)) {
      notify.error(i18n("Unable to update profile. File type is invalid."));
      return false;
    }
    if (file.size > 3000000) {
      notify.error(i18n("Unable to update profile. File size is too big."));
      return false;
    }
    return true;
  },

  _checkBio(bio) {
    let notify = this.get('notify');
    if (bio !== null && bio.length > 300) {
      notify.error(i18n("Unable to update profile. Description is too long (maximum is 300 characters)"));
      return false;
    }
    return true;
  }
});
