/** This file is part of Reactor.
 *  Copyright (c) 2020-2025 Kedron Holdings LLC, All Rights Reserved.
 *  Reactor is not public domain or open source. Distribution or derivative works are expressly prohibited.
 */

export const version = 25293;

const BUILDVERSION = "latest-26120-11db5cb2";

import { _T } from './i18n.js';
import { getAuthInfo } from './reactor-ui-common.js';

function readyHandler() {
    console.log("reactor-ui.js:readyHandler()");

    // Destroy any current stored session.
    const auth = getAuthInfo();
    if ( auth ) {
        $( 'div#message' ).text( _T(["#login-goodbye","You have been logged out."]) );
        try {
            $.ajax( "/api/v1/deauthorize", {
                method: "GET",
                beforeSend: function( xhr ) { xhr.setRequestHeader( "Authorization", "Bearer " + auth.token ); }
            }).done( () => {
                // Nada
            }).fail( (e) => {
                console.log( "deauth", auth, e );
            });
        } catch ( err ) {
            console.error( err );
        }

    }
    document.cookie = "reactor-session=; path=/; max-age=0;";

    // Apply localization
    $( 'span#username-prompt' ).text( _T(["#login-username-prompt","Username"]) );
    $( 'span#password-prompt' ).text( _T(["#login-password-prompt","Password"]) );
    $( 'label[for=rememberme]' ).text( _T(['#login-remember-me',"Remember me"]) );
    if ( ! BUILDVERSION.startsWith( '###' ) ) {
        $( '#reactor-buildversion' ).text( `Build ${BUILDVERSION}` );
    }
    $( 'button#action-auth' ).text( _T(['#login-button-text', 'Log In']) );

    $( '#license' ).on( 'click', () => {
        var $dlg = $( '#lic-modal' );
        $( '.modal-title', $dlg ).text( "Reactor License" );
        $( '.modal-body', $dlg ).text( "Loading..." );
        $( '.re-close', $dlg ).toggle( true );
        $( 'button:not([data-dismiss="close"])', $dlg ).on( 'click.reactor', function( event ) { /* ??? shouldn't that say data-dismiss="modal" ? */
            var $el = $( event.target );
            var index = $el.data( 'index' );
            $( '#lic-moda' ).data( 'event', index ).modal( 'hide' );
            return false;
        });
        $dlg.on( 'hidden.bs.modal.reactor', function( /* event */ ) {
            // const t = $dlg.data( 'event' ) || "";
            $( '*', $dlg ).off( '.reactor' );
        });
        $dlg.modal( 'show' );
        $.ajax({
            url: '/license'
        }).done( data => {
            $( '.modal-body', $dlg ).text( data );
        }).fail( () => {
            $( '.modal-body', $dlg ).text( "Please see LICENSE.md in the distribution package." );
        });
    });

    // Remember Me display
    try {
        const d = JSON.parse( localStorage.getItem( "reactor-login" ) );
        console.log("Loaded local storage", d);
        if ( d && d.username ) {
            $( 'input#username' ).val( d.username || "" );
            $( 'input#rememberme' ).prop( 'checked', true );
        } else {
            $( 'input#username' ).val( "" );
            $( 'input#rememberme' ).prop( 'checked', false );
            localStorage.removeItem( 'reactor-login' );
        }
    } catch ( err ) {
        console.error("local storage for reactor login:", err );
        $( 'input#username' ).val( "" );
        $( 'input#rememberme' ).prop( 'checked', true );
        localStorage.removeItem( 'reactor-login' );
    }

    const P = new URLSearchParams( window.location.search );
    $( 'button#action-auth' ).data( 'redir', "" ).attr( 'data-redir', "" );
    if ( P.get('redir') ) {
        const RP = P.get( 'redir' );
        console.log("RP",RP,typeof RP);
        if ( RP.indexOf( "login.html" ) < 0 ) {
            $( 'button#action-auth' ).data( 'redir', RP ).attr( 'data-redir', RP );
        }
    }

    $( 'button#action-auth' ).on( 'click', ( ev ) => {
        const $btn = $( ev.currentTarget );
        const re = /^\s*$/;
        const user = $( 'input#username' ).val();
        const pass = $( 'input#password' ).val();
        if ( re.test( user ) || re.test( pass ) ) {
            $( 'div#message' ).text( _T(["#login-user-pass-reqd", "Username and password are required."]) )
                .css( { 'color': '#f00', 'font-weight': 'bold' } );
            return;
        }

        $btn.prop( 'disabled', true );
        $( 'div#message').text( _T(["#login-please-wait", "Please wait..."]) )
            .css( { 'color': '', 'font-weight': '' } );

        $.post({
            url: "/api/v1/authorize",
            data: {
                username: user,
                password: pass
            }
        }).done( ( data ) => {
            // Remember me???
            if ( $( 'input#rememberme' ).prop( 'checked' ) ) {
                console.log("Setting local storage");
                localStorage.setItem( 'reactor-login', JSON.stringify( { username: user } ) );
            } else {
                console.log("Clearing local storage");
                localStorage.removeItem( 'reactor-login' );
            }

            if ( Array.isArray( data.applications ) && data.applications.length > 0 ) {
                // Check application.
                if ( 1 === data.applications.length && "boolean" === typeof data.applications[0] ) {
                    if ( false === data.applications[0] ) {
                        // No applications allowed.
                        $( 'div#message' ).text( _T(["#login-not-permitted","You do not have permission for this resource."]) )
                            .css( { 'color': '#f00', 'font-weight': 'bold' } );
                        return;
                    }
                    // All applications are permitted.
                } else {
                    let P = $btn.data( 'redir' ) || "";
                    if ( "" === P && 1 === data.applications.length && "false" !== data.applications[0] ) {
                        P = data.applications[0] || "reactor";
                        $btn.data( 'redir', '/'+P ).attr( 'data-redir', '/'+P );
                    } else {
                        let k = P.indexOf( '/', 1 );
                        if ( k < 0 ) {
                            P = "reactor";
                            $btn.data( 'redir', '/'+P ).attr( 'data-redir', '/'+P );
                        } else {
                            P = P.slice( 1, k );
                        }
                    }
                    if ( ! data.applications.includes( P ) ) {
                        $( 'div#message' ).text( _T(["#login-not-permitted","You do not have permission for this resource."]) )
                            .css( { 'color': '#f00', 'font-weight': 'bold' } );
                        return;
                    }
                }
            }

            document.cookie = "reactor-session=" +
                encodeURIComponent( JSON.stringify( { user: data.user, token: data.token, applications: data.applications } ) ) +
                `; path=/; max-age=${90*86400};${document.location.href.startsWith('https:')?" secure;":""}`;

            if ( $btn.data( 'redir' ) ) {
                window.location.href = $btn.data( 'redir' );
            } else {
                window.location.href = '/reactor';  // redir?
            }
        }).fail( (a, b, c) => {
            // console.error("a=",a,"b=",b,"c=",c);
            console.log("a=", a, "b=", b, "c=", c);
            let msg = a.statusText;  // starting point
            if ( 401 === a.status ) {
                msg = _T(["#login-auth-fail","Your username and/or password are incorrect."]);
            } else {
                msg = _T(["#login-general-error","Something went wrong. Try again."]);
                console.error("Authorization request failed:", a.status, a.statusText, a.readyState);
                console.error(a);
            }
            $( 'div#message' ).text( msg ).css( { 'color': '#f00', 'font-weight': 'bold' } );
        }).always( () => {
            $btn.prop( 'disabled', false );
        });
    });

    $( document ).on( 'keypress', ( e ) => {
        if ( 13 === e.which ) {
            $( 'button#action-auth' ).trigger( 'click' );
            return false;
        }
    });
}

jQuery( readyHandler );
