/* globals Twitch */
import jQuery from 'jquery';
import { assign } from 'ember-platform';
import getServer from 'web-client/mirage/get-server';

function setCookies(user) {
  window.cookie.set('api_token', user.id);
  window.cookie.set('login', user.login);
  window.cookie.set('name', user.name);
}

function clearCookies() {
  window.cookie.remove('api_token');
  window.cookie.remove('login');
  window.cookie.remove('name');
}

const DEFAULT_USER = {
  login: 'twitch',
  // flag that tells /api/me mirage route to return this user
  _is_signed_in_: true
};

export function stubLogin(userData = {}) {
  let userParams = assign(assign({}, DEFAULT_USER), userData);
  userParams.name = userParams.name || userParams.login;

  // reset cached promise so that current user is fetched via /api/me every time
  Twitch.user.reset();

  let sessionUser = getServer().create('session-user', userParams);
  userParams.id = sessionUser.id;

  getServer().create('channel-ember-data', userParams);
  getServer().create('friendship-user', userParams);

  userParams._id = userParams.id;
  delete userParams.id;
  getServer().create('user', userParams);

  Twitch.api.config.login = sessionUser.login;
  setCookies(sessionUser);

  return sessionUser;
}

// Simulates the condition where there is no logged-in user.
// Can be used after `stubLogin` for individual tests that require
// no logged-in user in the midst of a module that uses
// `stubLogin` in its `beforeEach`.
export function stubLogout() {
  Twitch.user.reset();

  clearCookies();

  Twitch.api.config.login = null;
}

let originalJQueryLogin;
let stubbedLoginModal = {};

// Stubs the login modal/overlay that is displayed by `$.login`
// Returns an object with a `isDisplayed` property that can be
// used to assert that the modal is shown.
// `restoreLoginModal` must be called after stubbing. moduleForAcceptance
// already does so in its `afterEach`.
export function stubLoginModal() {
  originalJQueryLogin = jQuery.login;
  jQuery.login = () => stubbedLoginModal.isDisplayed = true;
  return stubbedLoginModal;
}

export function restoreLoginModal() {
  if (originalJQueryLogin) {
    jQuery.login = originalJQueryLogin;
  }

  originalJQueryLogin = null;
  stubbedLoginModal = {};
}

export function restoreLogin() {
  Twitch.user.reset();
}
