/*
User login and logout controller

@copyright (c) Copyright 2013-2017 Dorian Pula
@license AGPL v3
@author Dorian Pula [dorian.pula@amber-penguin-software.ca]
*/

/* eslint-disable react/jsx-handler-names */

import {h, Component} from 'preact';  /** @jsx h*/

import {Button, Alert, Input, Form, Label, FormGroup, Col} from 'reactstrap';
import FontAwesome from 'react-fontawesome';
import {connect} from 'preact-redux';
import PropTypes from 'prop-types';

import {loginUser, logoutUser} from '../actions';
import appStore from '../store';


export class UserLoginView extends Component {
  static get propTypes() {
    return {
      isUserLoggedIn: PropTypes.bool,
      fullName: PropTypes.string,
      externalError: PropTypes.string,
    };
  }

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: '',
      errorMessage: '',
    };
    this.handleLoginAttempt = this.handleLoginAttempt.bind(this);
    this.updateErrorMessage = this.updateErrorMessage.bind(this);
    this.handleClearLoginForm = this.handleClearLoginForm.bind(this);
    this.handleLogoutUser = this.handleLogoutUser.bind(this);
    this.handleUsernameUpdate = this.handleUsernameUpdate.bind(this);
    this.handlePasswordUpdate = this.handlePasswordUpdate.bind(this);
    this.handleKeyboardLogin = this.handleKeyboardLogin.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    // TODO: Fix the transitions up, maybe have the login state as part of the app itself.
    if (nextProps.externalError !== '') {
      this.updateErrorMessage(nextProps.externalError);
    }

    if (nextProps.isUserLoggedIn === true) {
      this.handleClearLoginForm();
    }
  }

  handleLoginAttempt() {
    if (this.state.username === '' || this.state.password === '') {
      this.updateErrorMessage('Enter a username and password to login in...');
      return;
    }
    appStore.dispatch(loginUser(this.state.username, this.state.password));
  }

  updateErrorMessage(errorMessage='') {
    this.setState({errorMessage: errorMessage});
  }

  handleClearLoginForm() {
    this.setState({username: '', password: '', errorMessage: ''});
  }

  handleLogoutUser() {
    appStore.dispatch(logoutUser());
  }

  handleUsernameUpdate(event) {
    this.setState({username: event.target.value});
  }

  handlePasswordUpdate(event) {
    this.setState({password: event.target.value});
  }

  handleKeyboardLogin(event) {
    if (!this.state.displayLoginModal || event.key !== 'Enter') {
      return;
    }

    if (this.state.username === '' || this.state.password === '') {
      this.updateErrorMessage('Enter a username and password to login in...');
      return;
    }
    appStore.dispatch(loginUser(this.state.username, this.state.password));
  }

  render() {
    let loggedIn = this.props.isUserLoggedIn;
    let loginMessage = loggedIn ? 'logout' : 'login';
    let loginIcon = loggedIn ? (<FontAwesome name='sign-in'/>) : (<FontAwesome name='sign-out'/>);

    let errorDisplay = '';
    if (this.state.errorMessage !== undefined && this.state.errorMessage !== '') {
      errorDisplay = (<Alert color='danger'>{ this.state.errorMessage }</Alert>);
    }

    let loginButtonDisabled = this.state.username === '' || this.state.password === '';

    let loginForm = loggedIn ? (<div />) :
      (
        <div onKeyPress={ this.handleKeyboardLogin }>
          {errorDisplay}
          <Form horizontal>
            <FormGroup row>
              <Col xs='2'>
                <Label for='username'>Username</Label>
              </Col>
              <Col xs='10' >
                <Input
                  id='username'
                  type='text'
                  placeholder='Username'
                  value={ this.state.username }
                  onChange={ this.handleUsernameUpdate } />
              </Col>
            </FormGroup>
            <FormGroup row>
              <Col xs='2'>
                <Label for='password'>Password</Label>
              </Col>
              <Col xs='10'>
                <Input
                  id='password'
                  type='password'
                  placeholder='***'
                  value={ this.state.password }
                  onChange={ this.handlePasswordUpdate } />
              </Col>
            </FormGroup>
            <div style={{ display: 'flex', flexDirection: 'row', justifyContent: 'flex-end' }}>
              <Button
                color='warning'
                onClick={ this.handleClearLoginForm }
              >
                Cancel
              </Button>
              <span>&nbsp;</span>
              <Button
                color='primary'
                onClick={ this.handleLoginAttempt }
                disabled={ loginButtonDisabled }
              >
                Login
              </Button>
            </div>
          </Form>
        </div>
      );

    return (
      <div style={{ paddingTop: '50px' }}>
        <div className='text-center muted'>
          <FontAwesome name='user'/>
                    &nbsp;
                    Hello { this.props.fullName }!
                    &ensp;
          { loginIcon }
                    &nbsp;
                    Do you want to { loginMessage }?
        </div>
        { loginForm }
      </div>
    );
  }
}


export const ConnectedUserLogin = connect(
  (state) => {
    return {
      'fullName': state.user.profile !== undefined ? state.user.profile.fullName : 'Stranger',
      'isUserLoggedIn': state.user.token !== '',
      'externalError': state.user.accountState
    }
  }
)(UserLoginView);
