import $ from 'jquery';
import * as JSX from './jsx';
import * as user from './user';
import { GroupBox, Page } from './components';

export default function Login() {
  if( user.is_loggedin )
    return JSX.navigateParams( "/", {} );

  const url = new URL( window.location.href );
  const code = url.searchParams.get( "token" );
  let msg = "You should be redirected shortly...";
  if( !code ) {
    msg = "The link you followed is invalid.";
  }
  else {
    user.onLogin( code ).then( () => {
      JSX.navigateParams( '/terminal', {} );
    } ).catch( ( e: any ) => {
      $( "#login-msg" ).text( e.message );
    } );
  }

  return <Page>
    <GroupBox title="Login">
      <span id="login-msg">{ msg }</span>
    </GroupBox>
  </Page>
}
