/**
 * controllers/Auth.js
 *
 * @file Provides controller for Auth view
 *
 * @author Jessie Hildebrandt
 */

/* -------------------------------------------------------------------------- */
/* Local module imports */

import { formDataFromObject, sleep } from '../utils/utils.js';

/* -------------------------------------------------------------------------- */
/* Controller implementation */

/**
 * Controller for Auth component
 */
const Auth = {

    /* ---------------------------------- */
    /* init */

    /**
     * Initialize the controller
     */
    init()
    {

        Auth.password = '';

        Auth.isError = false;
        Auth.isWaiting = false;

    },

    /* ---------------------------------- */
    /* reset */

    /**
     * Reset the controller
     */
    reset()
    {
        Auth.init();
    },

    /* ---------------------------------- */
    /* updatePassword */

    /**
     * Update the password stored in the controller
     *
     * @param {string} value - The value to update the password to
     */
    updatePassword( value )
    {
        Auth.password = value;
        Auth.isError = false;
    },

    /* ---------------------------------- */
    /* tryLogIn */

    /**
     * Attempt to authenticate with the stored password
     */
    async tryLogIn()
    {

        // Signal to the component that activity is occurring
        Auth.isError = false;
        Auth.isWaiting = true;
        m.redraw();

        // Prevent the auth page from blinking away too quickly
        await sleep( 150 );

        try
        {

            // Attempt to start a new session by submitting the password to the API
            const response = await m.request( {
                method: 'POST',
                url: '/shorten/api/session',
                body: formDataFromObject( { password: Auth.password } ),
                background: true
            } );

            // Success, reroute to the App view
            m.route.set( '/app' );

        }
        catch
        {

            // Signal to the component that the API responded with an error
            Auth.isError = true;
            Auth.isWaiting = false;
            m.redraw();

        }

    }

};

/* -------------------------------------------------------------------------- */
/* Export */

export { Auth };
