# libs
window.$ = require('jquery')

# import bootstrap
require './style/custom.scss'
require 'bootstrap/js/dist/alert'

window.showAlert = (level, content) ->
  ($ '.alert').alert 'close'

  ($ '#alert-area').append ($ '<div>',
    class:  "alert alert-#{level} alert-dismissible fade show"
    role:   'alert'
  .append content, ($ '<button>',
    type:   'button'
    class:  'close'
    'data-dismiss': 'alert',
    'aria-label': 'Close'
  .append ($ '<span>',
    'aria-hidden': 'true'
  .append '&times;'
  )))

# on load
$ ->
  # reset forms
  $('form').each ->
    @fullReset = ->
      $('input', @).each ->
        $(@).removeClass 'is-invalid'
        $(@).removeClass 'is-valid'
      @reset()

  # login form
  $('form[name="login"]').submit (event) ->
    that = @
    # inhibit normal form submission
    event.preventDefault()

    # gather form data
    login = $('input[name="login"]', @)
    password = $('input[name="password"]', @)

    # transmit form data
    $.post '/login',
      login: login.val()
      password: password.val()
    .done (data) ->
      if data.status == 'ok'
        that.fullReset()
        showAlert 'success', "successfully logged in '#{data.login}'"
        location.reload()

      else
        switch data.text
          when 'login'
            showAlert 'warning', 'Invalid username and/or password.'
            login.addClass 'is-invalid'
            password.addClass 'is-invalid'
          when 'db' or 'hash'
            showAlert 'danger', 'Internal failure, try again later.'
          else
            showAlert 'danger', 'Unknown failure. Can you reproduce this?'

  # registration form
  $('form[name="register"]').submit (event) ->
    that = @
    # inhibit normal form submission
    event.preventDefault()

    # gather form data
    login = $('input[name="login"]', @)
    password = $('input[name="password"]', @)
    confirm = $('input[name="confirm"]', @)

    # check form data
    if password.val() != confirm.val()
      confirm.addClass 'is-invalid'
      confirm.focus()

    else
      # transmit form data
      $.post '/register',
        login: login.val()
        password: password.val()
      .done (data) ->
        if data.status == 'ok'
          that.fullReset()
          showAlert 'success', "successfully registered '#{data.login}'"

        else
          switch data.text
            when 'invalid'
              showAlert 'warning', 'Invalid user input. Please provide username AND password.'
              login.addClass 'is-invalid'
              password.addClass 'is-invalid'
              login.focus()
            when 'hash'
              showAlert 'danger', 'Internal failure, try again later.'
            when 'db'
              showAlert 'danger', 'Internal failure or user name already taken.'
              login.addClass 'is-invalid'
              login.focus()
            else
              showAlert 'danger', 'Unknown failure. Can you reproduce this?'
