import { Template } from './template.js';
import { FormCallbacks, RouteMWS } from './auth2.js';
// import { HSDropdown} from '@preline/dropdown';

/* import { headerTemplate, footerTemplate, userData, utils } from './newtemplate.js';

document.getElementById('header').innerHTML = headerTemplate;
document.getElementById('footer').innerHTML = footerTemplate;

console.log(`User's name is ${userData.name}`);
console.log(`Today's date is ${utils.formatDate(new Date())}`);
 */


COGNITO.staff_login_url = COGNITO.staff_url + 'login?' + new URLSearchParams(STAFF_LOGIN_PARAMS).toString();
COGNITO.staff_logout_url = COGNITO.staff_url + 'logout?' + new URLSearchParams(STAFF_LOGOUT_PARAMS).toString();

COGNITO.client_login_url = COGNITO.client_url + 'login?' + new URLSearchParams(CLIENT_LOGIN_PARAMS).toString();
COGNITO.client_logout_url = COGNITO.client_url + 'logout?' + new URLSearchParams(CLIENT_LOGOUT_PARAMS).toString();


const USER_TYPE = COGNITO.user_type;
let LOGIN_URL = COGNITO[`${COGNITO.user_type}_login_url`];
// console.log('the usertype is: ', USER_TYPE, LOGIN_URL);

configurePageRoutes();

function router(pg, cb, targetWrap){
    
    let path = pg.pathname;
    let qs = pg.querystring;
    let route = apiuri+path;
    let wrap = targetWrap || 'datawrap';
    
    console.log('in ROOUTER path:', pg);
    // return false;
    if( !document.getElementById(wrap) ){
        console.error("Target wrap not found: ", wrap );
        return;
    }
    if(route){
       
        document.getElementById(wrap).innerHTML = Template.spinner;

        getRemoteData(route)
        .then(data => {
            console.log('routedata:', data);
            cb(data);
        })
        .catch(error => {
            console.error('Error:', error);
        });

    }
}



document.addEventListener("DOMContentLoaded", function() {
    // console.log(Template);
    // if(isLoggedIn()) fetchAuthStaff();
    configureMarkup();

    document.getElementById('modalAppendWrap').insertAdjacentHTML('beforeend', Template.modal);
    // document.getElementById('flowbiteModalAppendWrap').insertAdjacentHTML('beforeend', Template.flowbiteModal);

    document.addEventListener('change', function(event) {
        // Check if the event target is a select element
        if (event.target.id === 'SubmittedVendees') {
            let sel = event.target;
            // Handle the change event


            
            const all_vendees = Data.get('all_vendees_keyed', true);

            console.log('in CHANGE EVENT, all_vendees:', all_vendees);

            let chosen = all_vendees[ sel.value ];
            console.log('chosen:', chosen);
            if(chosen){
                document.getElementById('MinLog').value = chosen.min_log || '';
                document.getElementById('ShortVendee').value = chosen.short_vendee || '';
                document.getElementById('VendeeName').value = chosen.vendee_name || '';
                document.getElementById('Email').value = chosen.tech_email || '';
            }else{
                document.getElementById('MinLog').value = '';
                document.getElementById('ShortVendee').value = '';
                document.getElementById('VendeeName').value = '';
                document.getElementById('Email').value = '';
            }

            // document.getElementById('BizOwner').value = all_clients[sel.value].BizOwner || '';

            // console.log(chosen);
        }
    });


    document.addEventListener('submit', function(event) {
    if (event.target.tagName.toLowerCase() === 'form') {
        event.preventDefault();

        if( !confirm("Are you sure you want to submit new information?") ) return false;


        let f = event.target, cb = f.getAttribute('cb'), method = f.getAttribute('method');
        


        let formData = new FormData(f);
        formData.delete('SubmittedVendees');
        let jsonObject = {};
        for (const [key, value]  of formData.entries()) {
            jsonObject[key] = value;
        }

    
        // console.log(f, 'method:', f.method, 'attrMethod:', f.getAttribute('method'), 'action:', f.action, 'dataset:', f.dataset);

        // return false;
        
        console.log('URI: ', method, " ", f.action, 'JSON Event Body:', jsonObject);
        fetch(f.action, {
            method: method,
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${getAccessToken()}`
            },
            body: JSON.stringify(jsonObject)
        })
        .then(response => response.json())
        .then(result => {
            console.log('res:', result, 'incoming:', result.body, 'cb:', cb);

            // return false;

            if (typeof FormCallbacks[cb] === 'function') {
                FormCallbacks[cb](f, result);
            }            
                
        })
        .catch(error => {
            console.error('Error:', error);
        });
    }
});

    
    


    document.body.addEventListener('show.te.modal', (e) => {
        // if (e.target.classList.contains('your-modal-class')) {
            // console.log('Modal Event');
            const button = e.relatedTarget;
            const modalbody = e.target;
            const dataset = button.dataset;
            console.log('btn dataset:', dataset);
            const cb = dataset.teCallback;//button.getAttribute('data-te-callback');
            
            
            modalbody.querySelector('#innerModalWrap').innerHTML = Template.spinner;

  
            const modalTitle = modalbody.querySelector('#modalWrapLabel');
            modalTitle.textContent = dataset.teTitle;//button.getAttribute('data-te-title');

                if (typeof FormCallbacks[cb] === 'function') {
                    FormCallbacks[cb](button, modalbody);
                }else{
                    console.error(FormCallbacks[cb] +' ('+cb+') is not a function')
                }
        

    });    

});



function configurePageRoutes(){

    const API = {

        always: function (ctx, next) {
            console.log("*** Always loaded", ctx.path, "***");
            next();
        },
        
        index: function () {
            console.log("Index loaded");
        },
        
        staffzone: function () {
            
            console.log("Welcome again to the Staff Zone Dashboard!");
        },
        
        clientzone: function () {
            
            console.log("Welcome again to the Client Zone Dashboard!");
        },
        
        stafflogin: function () {
            console.log("About to staff login:", COGNITO.staff_login_url);
            Data.set('cog_user_type', 'staff');
    
            // return;
            window.location = COGNITO.staff_login_url;
            // window.open(COGNITO.staff_login_url, 'Sign In Here' , 'top=100, left=100, width=400, height=450');
            return;
        },
        
        clientlogin: function () {
            console.log("About to client login:", COGNITO.client_login_url);
            Data.set('cog_user_type', 'client');
            window.location = COGNITO.client_login_url;
            // window.open(COGNITO.client_login_url, 'Sign In Here' , 'top=100, left=100, width=400, height=450');
            return;
        },
        
        stafflogout: function () {
            console.log("About to logout staff:", COGNITO.staff_logout_url);
          
            clearCookies();
            // return;
            window.location = COGNITO.staff_logout_url;
        },
        
        clientlogout: function () {
            console.log("About to logout client:", COGNITO.client_logout_url);
          
            clearCookies();
            // return;
            window.location = COGNITO.client_logout_url;
        },
        
        combined_vendees: function(pg){
            console.log("combined_vendees Loaded");
            router(pg, function(data){
                processJoinData( data.body );
            });
        },
        rawvendees: function (pg) {
            console.log("rawvendees Loaded");
            router(pg, function(data){
                processTableData( 'rawvendees', data.body, {id: 'rawvendees-table'} );
            });
        },
        vendees: function (pg) {
            console.log("vendees Loaded");
            router(pg, function(data){
                processTableData( 'vendees', data.body, {id: 'vendees-table'} );
            });
        },
        vendee: function (pg, next) {
            console.log("vendee (single) Loaded: ");
            router(pg, function(data){
                console.log('singlereturn:', data);
            });
        },
        
        vcollection: function (pg, next) {
            console.log("vendee (collection) Loaded: ", apiuri + '/' + pg.path);
        
            
            getRemoteData(apiuri + pg.path)
                .then(colldata => {
                    console.log('collectiondata:', colldata);

                    if (document.getElementById('collectionWrap')) {
                        console.log('Yes CollWrap!!');
                        buildVendeeCollectionPage(colldata);
                    } else {
                        console.log('No CollWrap, needs to Load List:');
                        
                        pg.pathname = '/vlist';
                        router(pg, function (listdata) {
                            console.log('list return in /vcollection:', listdata);
                            buildVendeeList(listdata);
                            buildVendeeCollectionPage(colldata);
                        });
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });

            return;
            router(pg, function(data){
                console.log( 'collectiondata:', data);
                return;
                buildVendeeCollectionPage(data);
            }, 'collectionWrap');
        },
        
        vlist: function (pg, next) {
            console.log('vlist ctx:', pg);
            // pg.pathname = '/vlist';
            router(pg, function(data){
                console.log('list return in /vlist:', data);
                buildVendeeList(data);
                // next();
            });

        },
        notfound: function (pg) {
            console.log('404:  Not Found!!!');
            // router(pg);
        }
    }
    
    
    let openMware = [RouteMWS.mw_insertLogInHeaderMarkup, RouteMWS.mw_insertHomeMarkup];
    let staffAuthMware = [RouteMWS.checkAuth, RouteMWS.mw_fetchAuthStaff, RouteMWS.mw_insertLocalStaffMarkup];
    let clientAuthMware = [RouteMWS.checkAuth, RouteMWS.mw_fetchAuthClient, RouteMWS.mw_insertLocalClientMarkup];
    let notFoundMware = [RouteMWS.mw_insertLogInHeaderMarkup, RouteMWS.mw_insert404Markup];

    // page( '*', .., API.always );
    page( '/', ...openMware, API.index );
    page( '/clientlogin', API.clientlogin );
    page( '/clientlogout', API.clientlogout );
    page( '/clientzone', ...clientAuthMware, API.clientzone );

    page( '/stafflogin', API.stafflogin );
    page( '/stafflogout', API.stafflogout );
    page( '/staffzone', ...staffAuthMware, API.staffzone );
    page( '/combined_vendees', ...staffAuthMware, API.combined_vendees );
    page( '/rawvendees', ...staffAuthMware, API.rawvendees );
    page( '/vendees', ...staffAuthMware, API.vendees );
    page( '/vlist/:id', ...staffAuthMware, API.vcollection );
    page( '/vlist', ...staffAuthMware, API.vlist );
    page( '/vendee/:id', ...staffAuthMware, API.vendee );
    page( '/vendee/:id/collection', ...staffAuthMware, API.vcollection );

    page('*', ...notFoundMware, API.notfound); 
    page();

}


