import {browserHistory} from 'react-router'
import Cookie from 'js-cookie'
import store from 'common/store'
import request from 'common/request'
import {get_url_parameter} from 'common/utilities'
import {redirect_to_after_login, login, logout} from 'actions/authentication'
import {get_logged_in} from 'selectors/authentication'
import {alert_info} from 'actions/display'
import init from 'common/init'

function action_redirect_after_login() {
  const {authentication: {redirect_to_after_login: path}} = store.getState()
  browserHistory.push(path)
  store.dispatch(redirect_to_after_login('/'))
}

function action_login_with_token(token) {
  store.dispatch(login(token))
  init()
}

export function action_login(email, password) {
  return request.post('recruiter_token', {auth: {email, password}})
  .then(({jwt: token}) => {
    Cookie.set('jwt', token, {expires: 366 * 20}) // cookie expires in 20 years
    action_login_with_token(token)
    action_redirect_after_login()
  })
  .catch(() => store.dispatch(alert_info("Mot de passe incorrect")))
}

export function action_reset_password(email) {
  return request.post('recruiters/reset_password', {email})
  .then(() => store.dispatch(alert_info("Mail de récupération de mot de passe envoyé")))
}

export function action_logout({redirect_after_logout = true} = {}) {
  Cookie.remove('jwt')
  store.dispatch(logout())
  if (redirect_after_logout) {
    browserHistory.push('/login')
  }
}

function is_logged_in({login_if_not_logged_in = true} = {}) {
  if (get_logged_in(store.getState())) {
    return true
  }
  const token = Cookie.get('jwt')
  if (token) {
    if (login_if_not_logged_in) {
      action_login_with_token(token)
    }
    return true
  }
  return false
}

export function try_logging_in() {
  if (is_logged_in()) {
    action_redirect_after_login()
  }
}

export function action_redirect_if_not_logged_in(path) {
  if (!is_logged_in()) {
    store.dispatch(alert_info("Veuillez vous connecter"))
    store.dispatch(redirect_to_after_login(path))
    browserHistory.push('/login')
  }
}

export function action_update_password(password) {
  return request.post(`recruiters/update_password`, {token: get_url_parameter('token'), password})
  .then(({email}) => action_login(email, password))
  .then(() => store.dispatch(alert_info("Votre mot de passe a été mis à jour")))
}

export function action_check_reset_password_token() {
  return request.get(`recruiters/check_reset_password_token`, {token: get_url_parameter('token')})
}

export function action_accept_invitation(password) {
  return request.post(`recruiters/accept_invitation`, {token: get_url_parameter('token'), password})
  .then(({email}) => action_login(email, password))
}

export function action_check_invitation_token() {
  return request.get(`recruiters/check_invitation_token`, {token: get_url_parameter('token')})
}

export function action_get_public_profile(email) {
  return request.get(`public_profile`, {email})
}
