<template>
    <p id="message" v-show="unauthorized">Unauthorized Access.</p>
</template>

    <script>
    // Supporting files
    import { issPageValues } from "@/router/router-constants/issPage-values";
    import { validateISSClientTag } from "@/helpers/clientauth-helper";
    import { useMainStore } from '@/store';

    export default {
        name: "entry-page",
        mixins: [],
        data() {
            return {
                unauthorized: false,
            }
        },
        setup() {
            const mainStore = useMainStore();
            mainStore.resetISSConfigState();
            mainStore.resetPageFields();
            return { mainStore };
        },
        mounted() {
            this.validateClientTagOnEntry();
        },          
        methods:
        {            
            navigateForward() {
                this.$router.navigate(
                    this.navigationScenarios.MOVE_FORWARD_ENTRY_PAGE,
                    this.$route
                );
            },
            parseQueryParms() {
                // Dump the query string parameters into an array. Remove casing on the key for easy compare.
                let queryStringParams = [];
                for ( let param in this.$route.query)
                {
                    queryStringParams[param.toLowerCase()] = this.$route.query[param];
                }
                return queryStringParams;
            },
            async validateClientTagOnEntry() {
                const queryStringParams = this.parseQueryParms();
                const clientTag = queryStringParams["clienttag"];
                const clientTagPresent = !!clientTag;
                let authorized = false;

                if ( clientTagPresent )
                {
                    const resp = await validateISSClientTag(clientTag);
                    
                    if ( resp?.data.active && resp?.data.accountName.length > 0 )
                    {
                        this.populateISSConfigValues(resp.data);

                        authorized = true;

                        if ( resp.data.parameters?.length > 0 )
                        {
                            const finalParams = this.combineClientParameters(resp.data.parameters, queryStringParams);
                            this.populateStoreItemsFromParams(finalParams);
                        }
                    }
                }

                this.unauthorized = !authorized;

                if ( authorized )
                {
                    // Forced full location redirect here. We do not want the entry page as part of the router/flow/path history.
                    window.location = "/?issPage=" + issPageValues.WELCOME_PAGE;
                }
            },
            populateISSConfigValues(data)
            {
                this.mainStore.issConfig.clientName = data.accountName;
                this.mainStore.issConfig.clientDisplayName = data.accountName; // Defaults to use the client name.
                this.mainStore.issConfig.accountNumber = data.accountNumber;
                this.mainStore.issConfig.styleSheet = data.styleSheet;
                this.mainStore.issConfig.isCoverageEnabled = data.coverageEnabled;

                // NOTE: This is only here for testing purposes. Will be removed and replaced by actual token/signature validation when work is completed.
                if ( data.authentication == "RSAToken")
                    this.mainStore.issConfig.isAuthenticated = true;

                try
                {
                    if(data.clientFlags)
                    {
                        const clientFlags = JSON.parse(data.clientFlags);

                        if ( clientFlags.TPAEnabled )
                        {
                            this.mainStore.issConfig.enableTPAFlow = true;
                        }

                        if ( clientFlags.ClientDisplayName != null )
                        {
                            this.mainStore.issConfig.clientDisplayName = clientFlags.ClientDisplayName;
                        }

                        if ( clientFlags.ClaimRegistrationRequired )
                        {
                            this.mainStore.issConfig.isClaimRegistrationRequired = true;
                        }
                    }
                }
                catch ( e )
                {
                    console.error("Error parsing client flags: " + e);
                }
            },
            combineClientParameters(configParams, queryStringParams)
            {
                let finalParams = [];

                try
                {
                    const clientParams = JSON.parse(configParams);

                    for ( let cparam in clientParams)
                    {
                        let cname = clientParams[cparam].toLowerCase();

                        for ( let qsparam in queryStringParams)
                        {
                            let qsname = qsparam.toLowerCase();

                            if ( cname === qsname )
                            {
                                finalParams[cname] = queryStringParams[cname];
                            }
                        }
                    }
                }
                catch ( e )
                {
                    console.error("Error combining client parameters: " + e);
                }

                return finalParams;
            },
            populateStoreItemsFromParams(params) {

                // Populate store items from parameters.
                for ( let param in params)
                {
                    let name = param.toLowerCase();
                    let value = params[param];

                    switch (name)
                    {
                        case "policynumber":
                            this.mainStore.order.policy.policyNumber = value;
                            this.mainStore.issConfig.disabledFields.policyNumber = true;
                            break;

                        case "policyzipcode":
                            this.mainStore.order.policy.policyZipCode = value;
                            this.mainStore.issConfig.disabledFields.policyZipCode = true;
                            break;

                        case "lossdate":
                            // NOTE: May need some date parsing logic in here depending on client.
                            this.mainStore.order.policy.dateOfLoss = value;
                            break;

                        case "successreturnurl":
                            this.mainStore.issConfig.successReturnURL = value;
                            break;

                        case "failurereturnurl":
                            this.mainStore.issConfig.failureReturnURL = value;
                            break;

                        // Not stored
                        case "timestamp":
                        case "token":
                        case "signature":
                            break;
                    }
                }
            }
        },
        computed:{ 
        },
        components: {
        },
    }
</script>

<style lang="scss">
#message {
    text-align: center;
}
</style>
