import * as JSX from './jsx';
import * as user from './user';

import $ from 'jquery';

import { GroupBox, Page, Spinner } from './components';

async function saveNickname() {
  const username = $( '#username-input' ).val() as string;
  const spinner = $( <Spinner /> );
  $( "#confirm-btn" ).append( spinner );

  if( username.length > 1 ) {
    try {
      await user.savePrefs( { nickname: username } );
      localStorage.removeItem( 'needs-setup' );
      JSX.navigateParams( "/terminal", {} );
    } catch( e: any ) {
      $( "#landing-error" ).text( e.message );
      $( "#landing-error" ).show();
    }
  }

  spinner.remove();
}

export default function FirstLanding() {
  if( user.settings && user.settings.nickname && user.settings.nickname.length > 1 )
    setTimeout( () => JSX.navigateParams( "/terminal", {} ) );

  if( !user.is_loggedin ) {
    setTimeout( () => JSX.navigate( "/" ) );
    return <Page>not logged in</Page>
  }

  return <Page>
    <GroupBox title="First configuration">
      <div>
        Welcome to axonbox.net
      </div>
      <div>
        Please input a username. This can be changed at any time.
      </div>
      <div id="landing-error" style="display: none"></div>
      <input type="text" id="username-input" maxlength="15" placeholder="username" />
      <div style="width: 100%; text-align: right; margin-top: -20px">
        <button style="width: 150px; margin-right: 5px; display: inline; height: 20px"
          class="settings-btn"
          id="confirm-btn"
          onclick={ saveNickname }
        >Confirm</button>
      </div>
    </GroupBox>
  </Page>
}
