import computed from 'ember-computed';
import injectService from 'ember-service/inject';
import Service from 'ember-service';
import $ from 'jquery';

export const API_VERSION = 5;
const API_LIMIT = 20;

export default Service.extend({
  api: injectService(),
  session: injectService(),
  offset: 0,
  moderators: [],
  bannedChannels: [],
  communityInfo: {},
  permissions: {},
  isEditing: false,

  isLeader: computed('communityInfo.owner_id', function() {
    let { isAuthenticated, userData } = this.get('session');
    if (isAuthenticated && userData) {
      return parseInt(this.get('communityInfo.owner_id')) === userData.id;
    }
    return false;
  }),

  _isAuthedWithCommunity(checkCommunity=true) {
    let { isAuthenticated, userData } = this.get('session');
    if (!isAuthenticated || !userData) {
      return false;
    }
    if (checkCommunity && !this.get('communityInfo._id')) {
      return false;
    }
    return true;
  },

  getCommunityInfo(name) {
    if (!name) {
      return {
        'name': '',
        'summary': '',
        'description': '',
        'rules': ''
      };
    }

    return this.get('api').request('get', `communities?name=${name}`,
      {},
      { version: API_VERSION }
    );
  },

  createCommunity(data) {
    if (!data || !this._isAuthedWithCommunity(false)) {
      return;
    }

    let community = {
      name: data.name,
      summary: data.summary,
      description: data.description,
      rules: data.rules
    };

    return this.get('api').request('post', `communities`,
      community,
      { version: API_VERSION }
    );
  },

  updateCommunity(data) {
    if (!data || !this._isAuthedWithCommunity()) {
      return;
    }

    let community = {
      summary: data.summary,
      description: data.description,
      rules: data.rules,
      email: data.email
    };

    return this.get('api').request('put', `communities/${this.get('communityInfo._id')}`,
      community,
      { version: API_VERSION }
    );
  },

  uploadCommunityBanner(encodedImageString) {
    if (!encodedImageString || !this._isAuthedWithCommunity()) {
      return;
    }

    // as stop gap, the image-upload is a base 64 encoded string
    return this.get('api').request('post', `communities/${this.get('communityInfo._id')}/images/cover`,
      { cover_image: encodedImageString },
      { version: API_VERSION }
    );
  },

  uploadCommunityAvatar(encodedImageString) {
    if (!encodedImageString || !this._isAuthedWithCommunity()) {
      return;
    }

    // as stop gap, the image-upload is a base 64 encoded string
    return this.get('api').request('post', `communities/${this.get('communityInfo._id')}/images/avatar`,
      { avatar_image: encodedImageString },
      { version: API_VERSION }
    );
  },

  deleteCommunityBanner() {
    if (!this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('delete', `communities/${this.get('communityInfo._id')}/images/cover`,
      {},
      { version: API_VERSION }
    );
  },

  deleteCommunityAvatar() {
    if (!this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('delete', `communities/${this.get('communityInfo._id')}/images/avatar`,
      {},
      { version: API_VERSION }
    );
  },

  getStreamsForCommunity(communityId) {
    if (!communityId) {
      return;
    }

    return this.get('api').request('get', `streams?limit=${API_LIMIT}&offset=${this.get('offset')}&community_id=${communityId}`,
      {},
      { version: API_VERSION }
    );
  },

  fetchMoreStreams(communityId) {
    this.incrementProperty('offset', API_LIMIT);
    return this.getStreamsForCommunity(communityId);
  },

  fetchModerators() {
    return this.get('api').request('get', `communities/${this.get('communityInfo._id')}/moderators`,
      {},
      { version: API_VERSION }
    );
  },

  addModerator(userId) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('put', `communities/${this.get('communityInfo._id')}/moderators/${userId}`,
      {},
      { version: API_VERSION }
    );
  },

  removeModerator(userId) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('delete', `communities/${this.get('communityInfo._id')}/moderators/${userId}`,
      {},
      { version: API_VERSION }
    );
  },

  checkPermission(communityId) {
    if (!communityId && !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').authRequest('get', `communities/${communityId}/permissions`,
      {},
      { version: API_VERSION }
    );
  },

  fetchBannedChannels() {
    return this.get('api').request('get', `communities/${this.get('communityInfo._id')}/bans?limit=100`,
      {},
      { version: API_VERSION }
    );
  },

  fetchTimedoutChannels() {
    return this.get('api').request('get', `communities/${this.get('communityInfo._id')}/timeouts?limit=100`,
      {},
      { version: API_VERSION }
    );
  },

  unbanUser(userId) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('delete', `communities/${this.get('communityInfo._id')}/bans/${userId}`,
      {},
      { version: API_VERSION }
    );
  },

  banUser(userId, reason) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('put', `communities/${this.get('communityInfo._id')}/bans/${userId}`,
      { reason },
      { version: API_VERSION }
    );
  },

  timeoutUser(userId, params={}) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('put', `communities/${this.get('communityInfo._id')}/timeouts/${userId}`,
      params,
      { version: API_VERSION }
    );
  },

  untimeoutUser(userId) {
    if (!userId || !this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('delete', `communities/${this.get('communityInfo._id')}/timeouts/${userId}`,
      {},
      { version: API_VERSION }
    );
  },

  broadcastToCommunity(channelId, communityUUID) {
    let { isAuthenticated, userData } = this.get('session');
    if (!isAuthenticated || !userData || !communityUUID) {
      return;
    }

    return this.get('api').request('put', `channels/${channelId}/community/${communityUUID}`,
      {},
      { version: API_VERSION }
    );
  },

  removeCurrentCommunity(channelId) {
    return this.get('api').request('del', `channels/${channelId}/community`,
      {},
      { version: API_VERSION }
    );
  },

  getChannelCommunity(channelId) {
    return this.get('api').request('get', `channels/${channelId}/community`,
      {},
      { version: API_VERSION }
    );
  },

  getTopCommunities(limit = 100, cursor = "") {
    return this.get('api').request('get', `communities/top?limit=${limit}&cursor=${cursor}`,
      {},
      { version: API_VERSION }
    );
  },

  getReportReasons() {
    let options = [];
    return $.get('/undefined/report_form').then(htmlString => {
      let html = $.parseHTML(htmlString);
      $.each(html, function(i, el) {
        $(el).find('option').each(function() {
          let option = $(this);
          options.push({
            value: option.val(),
            text: option.text()
          });
        });
      });
      return options;
    });
  },

  reportCommunity(data) {
    if (!data || !this._isAuthedWithCommunity()) {
      return;
    }

    let postData = {
      description: data.description,
      reason: data.reason
    };

    return this.get('api').request('post', `communities/${this.get('communityInfo._id')}/report`,
      postData,
      { version: API_VERSION }
    );
  },

  reportCommunityChannel(data) {
    if (!data || !this._isAuthedWithCommunity()) {
      return;
    }

    let postData = {
      channel_id: data.channel_id
    };

    return this.get('api').request('post', `communities/${this.get('communityInfo._id')}/report_channel`,
      postData,
      { version: API_VERSION }
    );
  },

  banCommunity() {
    if (!this._isAuthedWithCommunity()) {
      return;
    }

    return this.get('api').request('post', `communities/${this.get('communityInfo._id')}/tos_ban`,
      {},
      { version: API_VERSION }
    );
  }
});
