$ = jQuery
context = window
context.JK ||= {};

# events emitted:
# EVENTS.CHECKOUT_SIGNED_IN
# EVENTS.CHECKOUT_SKIP_SIGN_IN

context.JK.CheckoutSignin = class CheckoutSignin
  constructor: (app, root) ->
    @EVENTS = context.JK.EVENTS
    @rest = context.JK.Rest()
    @logger = context.JK.logger
    @app = app
    @root = root
    @emailInput = @root.find('input[name="email"]')
    @passwordInput = @root.find('input[name="password"]')
    @signinBtn = @root.find('.signin-submit')
    @skipSigninBtn = @root.find('.btnNext')
    @signinForm = @root.find('form.signin-form')

    # TODO: add Facebook login support

    throw "no root element" if not @root.exists()
    throw "no email element" if not @emailInput.exists()
    throw "no password element" if not @passwordInput.exists()
    throw "no signin btn" if not @signinBtn.exists()
    throw "no skip signin btn" if not @skipSigninBtn.exists()

    @signinForm.submit(@onSigninSubmit)
    @skipSigninBtn.click(@onSkipSignin)

  removeErrors: () =>
    @signinForm.removeClass('login-error');

  onSigninSubmit: () =>
    @logger.debug("attempting to signin")

    @removeErrors()

    @signinBtn.addClass('disabled')

    email = @emailInput.val()
    password = @passwordInput.val()

    @rest.login({email: email, password: password, remember_me: true})
      .done(@onLoginDone)
      .fail(@onLoginFail)

  onLoginDone: () =>
    @signinBtn.removeClass('disabled')
    $(this).triggerHandler(@EVENTS.CHECKOUT_SIGNED_IN, {})

  onLoginFail: (jqXHR) =>
    @signinBtn.removeClass('disabled')
    if jqXHR.status == 422
      @signinForm.addClass('login-error')
    else
      @app.notifyServerError(jqXHR, "Unable to log in. Try again later.")

  onSkipSignin: () =>
    $(this).triggerHandler(@EVENTS.CHECKOUT_SKIP_SIGN_IN, {})