import Component from 'ember-component';
import computed from 'ember-computed';
import Ember from 'ember';
import { htmlSafe } from 'ember-string';
import observer from 'ember-metal/observer';
import injectService from 'ember-service/inject';
import $ from 'jquery';

import { JTV_USER_PICTURES_404_USER_150X150_URL } from 'web-client/utilities/urls/static-cdn';

const { Handlebars } = Ember;
const { escapeExpression } = Handlebars.Utils;

export default Component.extend({
  classNames: ['js-moderation-card', 'moderation-card'],

  session: injectService(),

  // public things
  cardInfo: null,

  init() {
    this._super();
    this._fireTrackingEvent();
  },

  profileBannerBackgroundColorStyle: computed('cardInfo.user.profile_banner_background_color', function () {
    // `profile_banner_background_color` is user input sanitized on the server.
    //
    // relevant link: https://git-aws.internal.justin.tv/web/web/blob/b4f4429c33833250294d3714d214fd65eed9244c/app/controllers/api/channels_controller.rb#L119
    return htmlSafe(`background-color: ${ this.get('cardInfo.user.profile_banner_background_color') }`);
  }),

  profileBannerBackgroundImageStyle: computed('cardInfo.user.profile_banner', function () {
    return htmlSafe(`background-image: ${ escapeExpression(this.get('cardInfo.user.profile_banner')) };`);
  }),

  moderationTarget: computed.alias('cardInfo.user.id'),

  isIgnored: computed.alias('cardInfo.isIgnored'),

  profilePicture: computed('cardInfo.user.logo', function () {
    return this.get('cardInfo.user.logo') || JTV_USER_PICTURES_404_USER_150X150_URL;
  }),

  didInsertElement() {
    this._setPosition();
    this.$().draggable({handle: '.js-drag-handle'});
  },

  _setPosition: observer('cardInfo.renderTop', 'cardInfo.renderLeft', function () {
    this.$().offset({top: this.get('cardInfo.renderTop'), left: this.get('cardInfo.renderLeft')});
  }),

  _fireTrackingEvent: observer('cardInfo.user.id', function () {
    this.sendAction('trackAction', 'chat_card_open');
  }),

  actions: {
    message() {
      if (!this.get('session.isAuthenticated')) {
        return $.showAuthenticationOverlay('login', {
          mpSourceAction: 'whisper'
        });
      }
      this.sendAction('messageAction', this.get('cardInfo.user.id'));
    }
  }
});
