import DeprecatedGameModel from 'web-client/models/deprecated-game';
import computed from 'ember-computed';
import EditModal from 'web-client/components/edit-modal';
import injectService from 'ember-service/inject';
import CommunityGamesMixin from 'web-client/mixins/community-games';
import RSVP from 'rsvp';
import { GAME_NOT_FOUND } from 'web-client/utilities/game-names';
import { CancellationError } from 'web-client/utilities/error';

export default EditModal.extend(CommunityGamesMixin, {
  api: injectService(),
  globals: injectService(),
  contentTitle: computed.alias('content.status'),
  contentGame: computed.alias('content.game'),

  isBroadcasterLanguageChatEnabled: computed.readOnly('globals.broadcastLanguageChatEnabled'),

  rollbackAttributes() {
    let content = this.get('content');
    if (content && content.rollbackAttributes) {
      content.rollbackAttributes();
    }
  },

  click() {
    this._super();
    this.set('content.isLanguageRestricted', !!(this.get('content.room.restrictedChatLanguage')));
  },

  isValid() {
    return this._super()
      .then(({isValid, msg}) => {
        if (!isValid) {
          return {isValid, msg};
        }
        return this.isValidGame();
      });
  },

  isValidGame() {
    let name = this.get('content.game');
    if (!name) {
      return RSVP.resolve({isValid: true});
    }
    return DeprecatedGameModel.findByName(this.get('api'), name)
      .then(game => {
        if (this.get('content.game') !== name) {
          throw new CancellationError;
        }
        if (game.get('id') === GAME_NOT_FOUND) {
          return {isValid: false, msg: 'Please choose a supported game.'};
        }
        return {isValid: true};
      });
  },

  actions: {
    closeModal() {
      this.rollbackAttributes();
      this._super(...arguments);
    }
  }
});
