import {  Template, FormTemplate, FormStructure } from './template.js';


// COGNITO.user_type = Data.get('cog_user_type') || '';
// COGNITO.user_type = Data.get('cog_user_type') || '';

async function requestAuthToken(){
    if (COGNITO.code) {
        console.log('code is: ', COGNITO.code);
        Data.set('last_cog_code', COGNITO.code);
        const user_type = COGNITO.user_type;

        console.log('user_type:', user_type);
        if( !user_type ){
            console.error('NO user_type');
            return;
        }
        
        
        const data = {
            grant_type: 'authorization_code',
            client_id: COGNITO[`${user_type}_client_id`],
            // client_secret: COGNITO.client_secret,
            code: COGNITO.code,
            redirect_uri: COGNITO[`${user_type}_redirect_uri`]
        };
        console.log('TokenRequestData:', data);


        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: new URLSearchParams(data)
        };

        fetch(COGNITO[`${user_type}_token_url`], options)
            .then(response => response.json())
            .then(async d => {
                console.log('cognito data:', d);

                // const accessToken = data.access_token;
                // const refreshToken = data.refresh_token;
                // Data.set('old_cognito_creds', data);
                // Set cookies for each token

                // return;
                createCookies(d);
                // console.log( getAccessToken() );
                

                if(isLoggedIn()){
                    // let jwt = parseJwt( getAccessToken() );
                    // let accessToken = getCookie('cog_access_token');
                    // let idToken = getCookie('cog_id_token');
                    COGNITO.JWT = parseJwt( d.id_token );
                    if(COGNITO.JWT){
                        const USER = COGNITO.JWT.sub || '';
                        if(USER){
                    
                        getRemoteData(`${apiuri}/combined_vendees`)
                            .then(data => {
                                const vdata = data.body.rawvendees;
                    
                                let all_vendees_keyed = vdata.reduce((acc, obj) => {
                                    let newKey = obj.min_log + '-' + obj.short_vendee;
                                    acc[newKey] = obj;
                                    return acc;
                                }, {});
                    
                                Data.set('combined_vendees', data.body, true);
                                Data.set('all_vendees_keyed', all_vendees_keyed, true);

                                
                            })
                            .catch(error => {
                                console.error('Error:', error);
                            })
                            .finally(data => {
                                
                                console.log("USER:", COGNITO.JWT.sub );
                                setCookie('cog_user', COGNITO.JWT.sub, d.expires_in);
                                
                                window.location = `/${user_type}zone`;
                            });
                        

                            
                            // console.log('about to fetch auth memberr...')
                            // fetchAuthStaff();//we'll come back to this
                        }else{//process the Client bit

                        }
                    }else{
                        console.error( "'LoggedIn' WiTH NO VALID AccessToken:" );
                    }
                }else{
                    console.log('NOT Logged In');
                }

                // page.redirect('/dashboard');
                // window.location = '/dashboard';
                
                // Use the refresh token to obtain a new access token when the current one expires
            })
            .catch(error => console.error(error));

    }
}

await requestAuthToken();


// (function () {
 
// })();


function buildForm(elementArr, formAttributes = {}) {
    let f = '<form';
  
    for (let attr in formAttributes) {
      f += ` ${attr}="${formAttributes[attr]}"`;
    }
    f += ' class="">';

    elementArr.forEach(element => {
        let type = element.type;
        let id = element.id || element.name;
        let name = element.name || element.id;
        let label = element.label;
        let value = element.value;
        let xattr = element.xattr || "";

        f += '<div class="mb-4">'; // Start of div
        if(label){
            f += `<label for="${id}" class="block mb-2 text-primary-600">${label}</label>`;
        }
        if(type === 'select'){
            let options = element.options || {};
            let nullable = element.nullable;

             f += `<select name="${name}" id="${id}" class="border p-2 rounded w-full bg-blue-50" ${xattr}>`;
             if(nullable){
                f += `<option value="">--</option>`;
             }
             for (let option in options) {
                f += `<option value="${option}">${options[option]}</option>`;
              }
              f += '</select>';
        }else{
            if( type === 'textarea'){
                f += `<textarea name="${name}" id="${id}" class="border p-2 rounded w-full bg-blue-50" ${xattr}>${value}</textarea>`;
            }else{//others
                f += `<input type="${type}" name="${name}" id="${id}" value="${value}" class="border p-2 rounded w-full bg-blue-50" ${xattr}>`;
            }
        }
        f += '</div>'; // End of div

    });

    // Add a submit button at the end of the form
    
    f += FormTemplate.bottom
    f += '</form>';
  
    // console.log(f);
    return f;
  }
 
  function buildEditForm(formElements, formAttributes) {

    console.log('In buildEditForm, the formStructure:', formElements );
    if( !formElements ){
        console.log("No formElements supplied"); return "No formElements supplied";
    }
    
    if( !formAttributes ){
        console.log("No formAttribues supplied"); return "No formAttributes supplied";
    }
    
       return buildForm(formElements, formAttributes);

}


export const FormCallbacks = {
    populateEditForm: function(btn, modal){
            
        const rowdata = btn.dataset.rowdata;
        const rdata1 = JSON.parse(btn.dataset.rowdata || null);
        let method;

        console.log('therowdata:', rdata1);
        if(rdata1 && rdata1.PK && rdata1.SK){
            method = 'PATCH';
        }else{
            method = 'POST';
        }
        modal.querySelector('#innerModalWrap').innerHTML = buildEditForm(
            FormStructure.VendeeForm,
            {
            id: 'clientEditForm',
            class: 'w-full max-w-lg',
            cb: 'processEditFormSubmit',
            action: apiuri +'/vendee',
            method: method
        });


        if(!rowdata){
            console.log("NO rowdata found!!!");
            return;
        } 
        
        console.log("There is rowdata, continuing");

        const rdata = JSON.parse(rowdata);
        rdata.SubmittedVendees = rdata.MinLog+'-'+rdata.ShortVendee;
        
        const f = modal.querySelector('form');
        bindData(f, rdata);

},
    populateEditFormX: function(btn, modal){
        return;
        // console.log('btn:', btn, 'modal:', modal);
        getRemoteData(`${apiuri}/combined_vendees`)
        .then(data => {
            // console.log('data.setting...');
            const vdata = data.body.rawvendees;

            let all_vendees_keyed = vdata.reduce((acc, obj) => {
                let newKey = obj.min_log +'-'+ obj.short_vendee;
                acc[newKey] = obj; 
                return acc;
            }, {});

            // console.log('allkeyed:', all_vendees_keyed);
            
            
            Data.set('combined_vendees', data.body, true);
            Data.set('all_vendees_keyed', all_vendees_keyed, true);
            const rowdata = btn.dataset.rowdata;
            const rdata1 = JSON.parse(btn.dataset.rowdata || null);
            let method;

            console.log('therowdata:', rdata1);
            if(rdata1 && rdata1.PK && rdata1.SK){
                method = 'PATCH';
            }else{
                method = 'POST';
            }
            modal.querySelector('#innerModalWrap').innerHTML = buildEditForm(
                FormStructure.VendeeForm,
                {
                id: 'clientEditForm',
                class: 'w-full max-w-lg',
                cb: 'processEditFormSubmit',
                action: apiuri +'/vendee',
                method: method
            });


            if(!rowdata){
                console.log("NO rowdata found!!!");
                return;
            } 
            
            console.log("There is rowdata, continuing");

            const rdata = JSON.parse(rowdata);
            rdata.SubmittedVendees = rdata.MinLog+'-'+rdata.ShortVendee;
            
            const f = modal.querySelector('form');
            bindData(f, rdata);
        })
        .catch(error => {
            console.error('Error:', error);
        });

    }
    ,
    populateEntityForm: function(btn, modal){
        // console.log('btn:', btn, 'modal:', modal);
    
        
        const rowdata = btn.dataset.rowdata;
        const rdata1 = JSON.parse(btn.dataset.rowdata || null);
        let method;
        let entityType = rdata1.EntityType;


        console.log('drowdata:', rdata1);
        if(rdata1 && rdata1.PK && rdata1.SK){
            method = 'PATCH';
        }else{
            method = 'POST';
        }
        modal.querySelector('#innerModalWrap').innerHTML = buildEditForm(
            FormStructure[entityType],
            {
            id: 'clientEditForm',
            class: 'w-full max-w-lg',
            cb: 'processEditFormSubmit',
            // action: apiuri +'/'+entityType.toLowerCase()+'?dumpEvent=1',
            action: apiuri +'/'+entityType.toLowerCase(),
            method: method
        });


        if(!rowdata){
            console.log("NO rowdata found!!!");
            return;
        } 
        
        console.log("There is rowdata, continuing");

        const rdata = JSON.parse(rowdata);

        const f = modal.querySelector('form');

        if(f){

            bindData(f, rdata);
        }
    }
    ,
    processEditFormSubmit: function(f, res){
        // console.log('f:', f, 'res:', res);
        f.querySelector('[data-te-modal-dismiss]').click();
        page.show(window.location.pathname);     
    }   
}


export const RouteMWS = {
    checkAuth: function (ctx, next) {
        console.log('inside checkAuth...');
        if ( isLoggedIn()) {
            next();
        } else {
            console.log('About to redirect to login...');
            return;
            page.redirect(`/${COGNITO.user_type}login`)
            return;
        }
      },  
      
    /**STAFF */
    fetchAuthStaff: async function () {
        try {
            let sub = getCookie('cog_user');
            const data = await getRemoteData(apiuri + '/staff/' + sub);
            console.log('staffmemberdata:', data);
          return data;
        } catch (error) {
          console.error('Error:', error);
          // Rethrow the error or handle it as needed
          throw error;
        }
    },
    mw_fetchAuthStaff: async function (ctx, next) {
        ctx.authdata = await RouteMWS.fetchAuthStaff();
        next();
    },
    mw_insertLocalStaffMarkup: function(ctx, next){
        console.log('authdata:', ctx.authdata.email );
        if( !document.getElementById("collectionWrap") ){
            document.getElementById('authwrap').innerHTML = Template.staffLoggedInMarkup;
            document.getElementById('headerUserBox').innerHTML = Template.userLoggedInHeaderMarkup;
            document.getElementById('loggedInUserName').innerText = ctx.authdata.name;
            document.getElementById('loggedInUserEmail').innerText = ctx.authdata.email;
            activateDropdowns();
        }else{
            // alert("There's authwrap");
        } 
        next();
    },

    /**CLIENTS */
    fetchAuthClient: async function () {
        try {
            let sub = getCookie('cog_user');
            const data = await getRemoteData(apiuri + '/clients/' + sub);
            console.log('clientmemberdata:', data);
          return data;
        } catch (error) {
          console.error('Error:', error);
          // Rethrow the error or handle it as needed
          throw error;
        }
    },
    mw_fetchAuthClient: async function (ctx, next) {
        ctx.authdata = await RouteMWS.fetchAuthClient();
        next();
    },
    mw_insertLocalClientMarkup: function(ctx, next){
        if ( !ctx.authdata.email ){
            console.error("Error: Authenticated user not confirmed");
            return;
        } 
        // if( !document.getElementById("collectionWrap") ){
            document.getElementById('authwrap').innerHTML = Template.clientLoggedInMarkup;
            document.getElementById('headerUserBox').innerHTML = Template.userLoggedInHeaderMarkup;
            document.getElementById('loggedInUserName').innerText = ctx.authdata.email; 
            activateDropdowns();

            next();
    },

/***BOTH */
    mw_insertLogInHeaderMarkup: function(ctx, next){
        // document.getElementById('headerUserBox').innerHTML = Template.userLoginHeaderMarkup;
        next();
    },    
    mw_insertHomeMarkup: function(ctx, next){
        document.getElementById('authwrap').innerHTML = Template.homeMarkup;
        next();
    },    
    mw_insert404Markup: function(ctx, next){
        document.getElementById('authwrap').innerHTML = Template.notFoundMarkup;
        next();
    },
 }
