const waitingBig = new Image();
waitingBig.src = "img/waitingbig.gif";
const WAITINGBIG = '<img src="'+waitingBig.src+'" class="waitingbig" align="middle"/>';
const nigeriaStates = {
    "Abia": "Abia",
    "Adamawa": "Adamawa",
    "Akwa Ibom": "Akwa Ibom",
    "Anambra": "Anambra",
    "Bauchi": "Bauchi",
    "Bayelsa": "Bayelsa",
    "Benue": "Benue",
    "Borno": "Borno",
    "Cross River": "Cross River",
    "Delta": "Delta",
    "Ebonyi": "Ebonyi",
    "Edo": "Edo",
    "Ekiti": "Ekiti",
    "Enugu": "Enugu",
    "Gombe": "Gombe",
    "Imo": "Imo",
    "Jigawa": "Jigawa",
    "Kaduna": "Kaduna",
    "Kano": "Kano",
    "Katsina": "Katsina",
    "Kebbi": "Kebbi",
    "Kogi": "Kogi",
    "Kwara": "Kwara",
    "Lagos": "Lagos",
    "Nasarawa": "Nasarawa",
    "Niger": "Niger",
    "Ogun": "Ogun",
    "Ondo": "Ondo",
    "Osun": "Osun",
    "Oyo": "Oyo",
    "Plateau": "Plateau",
    "Rivers": "Rivers",
    "Sokoto": "Sokoto",
    "Taraba": "Taraba",
    "Yobe": "Yobe",
    "Zamfara": "Zamfara",
    "FCT": "Federal Capital Territory"
  };
  

function in_array(val, arr) {
    if (!Array.isArray(arr)) return null;
    var strval = val.toString();
    var thearr = arr.map(function(a) { return a.toString(); });
    
    if (thearr.indexOf(strval) >= 0) return true;
    else return false;
  }
  
function object2table(obj, colarr, tblattribs, cbmap){
  console.log('calling object2table with:', obj);

	let heads, T, celltxt;
  colarr = colarr || [];
  cbmap = cbmap || {}, cbmapkeys = Object.keys(cbmap);
  let xattr = '';
    for(let attr in tblattribs){
      xattr += `${attr}="${tblattribs[attr]}" `;
    }
    // console.log('XATTR:', xattr);
    // console.log(cbmap, cbmapkeys);
	
	T = `<table class="fullwidth rowtable" ${xattr}>`;
	if(typeof obj[0] != 'undefined' && obj[0] != null){
		T += '<thead><tr>';
		
		heads = colarr.length ? colarr : Object.keys(obj[0]);
		for(let h in heads){
            T += '<th>'+heads[h]+'</th>';
		}
		T += '</tr></thead>';
	}
	
	for(let i in obj){
		T += '<tr>';
		r = obj[i];
		for(var j in heads){
            var colkey = heads[j];
            // var pref = heads[j] === 'VendeeName' ? JSON.stringify(r) : '';
            celltxt = (r[ heads[j]] || '');

            if( in_array(colkey, cbmapkeys) ){
                cellcb = cbmap[ colkey ];
                
                // console.log(cellcb);
                if(typeof cellcb === "function") {
                   celltxt = cellcb(colkey, celltxt, r);//derive cell text from cb
                }else{
                    // console.log(typeof cellcb);
                }
            }
			T += '<td>'+celltxt+'</td>';			
		}
		T += '</tr>';
	}

	T += '</table>';
	
	return T;
}



  
  function bindData(f, data, cb){
    console.log('DATA in BindDATA:', data);

    var header = f.querySelector('#binddata-header');
    if(header) header.remove();
    
    var checkboxes = f.querySelectorAll('input[type=checkbox]');
    checkboxes.forEach(function(checkbox) {
        checkbox.checked = false;
    });
    
    for(var fld in data){
        var inp = f.querySelector('#'+fld) || f.querySelector('[name='+fld+']');
        
        if(inp && !inp.classList.contains('no-binding')){
            if(inp.type === 'checkbox'){
                var v = data[fld];
                inp.value === v ? inp.checked = true : inp.checked = false;
            }else{
                if(['INPUT', 'TEXTAREA', 'SELECT', 'BUTTON'].includes(inp.tagName)){
                    inp.value = data[fld];
                }else{
                    inp.textContent = data[fld];
                }
            }
        }
    }
    if(cb) cb(f, data);
}

function filterObject(obj, keys) {
  return Object.fromEntries(
    Object.entries(obj).filter(([key]) => keys.includes(key))
  );
}

function filterObjKeys(arr, keys) {
    return arr.map(obj => {
        return keys.reduce((acc, key) => {
            if (obj.hasOwnProperty(key)) {
                acc[key] = obj[key];
            }
            return acc;
        }, {});
    });
}



function ltrim(str){
	if(str === null || str === undefined ) return '';
	if( /\r\n|\n|\r|\t|\s/.test( str.charAt(0) ) ){
		newstr=str.substring(1,str.length);
		ltrim(newstr);
	}else{
		newstr=str;	
	}

	return newstr;
}

function rtrim(str){
	if(str === null || str === undefined ) return '';
	if( /\r\n|\n|\r|\t|\s/.test( str.charAt( str.length-1 ) ) ){
		newstr=str.substring(0,str.length-1);
		rtrim(newstr);
	}else{
		newstr=str;	
	}
	return newstr;
}

function trim(str){
	return(ltrim(rtrim(str)));
}

function dateToLocale(format, dateString, timezone) {
    // Create a Date object
    timezone = timezone || 'Africa/Lagos';
    let date = new Date(dateString);
  
    // Convert to the specific timezone
    let localeDateString = date.toLocaleString("en-US", { timeZone: timezone });
  
    // Create a new Date object with the locale date string
    let localeDate = new Date(localeDateString);
  
    // Extract date parts
    let dd = String(localeDate.getDate()).padStart(2, '0');
    let MM = String(localeDate.getMonth() + 1).padStart(2, '0'); // Months are zero-based
    let yy = String(localeDate.getFullYear()).slice(-2);
    let yyyy = localeDate.getFullYear();
    let hh = String(localeDate.getHours()).padStart(2, '0');
    let mm = String(localeDate.getMinutes()).padStart(2, '0');
    let ss = String(localeDate.getSeconds()).padStart(2, '0');
  
    // Replace format string with date parts
    format = format.replace('YYYY', yyyy);
    format = format.replace('YY', yy);
    format = format.replace('MM', MM);
    format = format.replace('DD', dd);
    format = format.replace('hh', hh);
    format = format.replace('mm', mm);
    format = format.replace('ss', ss);
  
    return format;
  }
  

  async function getRemoteData(uri) {
    try {
      const options = {
        headers: {
            Authorization: `Bearer ${getAccessToken()}`
        }
      };
        const response = await fetch(uri, options);
        const data = await response.json();
        // console.log('first retrieval: ', data);
        return data;
    } catch (error) {
        console.error('API Error:', error);
    }
}

async function getUserIP(){
  try{

    fetch('https://ipinfo.io/json')
    .then(response => response.json())
    .then(data => {
      const userIP = data.ip;
      
      console.log("The IP is: ", userIP );
    })
    .catch(error => console.error('Error fetching IP:', error));
  } catch (e) {
    console.error('IP Error', e);
  }

}

function hideEl(el) {
  var elements = document.querySelectorAll(el);
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.visibility = "hidden";
  }
}

function showEl(el) {
  var elements = document.querySelectorAll(el);
  for (var i = 0; i < elements.length; i++) {
    elements[i].style.visibility = "visible";
  }
}

function parseJwt(token) {
  // Check if the token contains a dot character
  if (typeof token !== 'string' || token.indexOf('.') === -1) {
    console.log("This does not look like a JWT token");
    return null;
  }

  // Rest of your code for parsing the JWT token
  var base64Url = token.split('.')[1];
  var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
  var jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
      return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
  }).join(''));

  return JSON.parse(jsonPayload);
}


function deleteCookie(name) {
  document.cookie = `${name}=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;`;
}

function getAllCookies() {
  const cookies = document.cookie; // Get the cookie string
  const cookieArray = cookies.split(';'); // Split into an array of individual cookies

  // Create an object to store cookies
  const cookieObject = {};

  // Iterate over the array and parse each cookie
  for (let i = 0; i < cookieArray.length; i++) {
      const cookie = cookieArray[i].trim(); // Remove leading/trailing whitespaces
      const [name, value] = cookie.split('='); // Split each cookie into name and value

      // Decode the cookie value (in case it contains special characters)
      const decodedValue = decodeURIComponent(value);

      // Store the cookie in the object
      cookieObject[name] = decodedValue;
  }

  return cookieObject;
}

function deleteAllCookies() {
  var cookies = document.cookie.split(";");

  for (var i = 0; i < cookies.length; i++) {
      var cookie = cookies[i];
      var eqPos = cookie.indexOf("=");
      var name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie;
      document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT";
  }
}

function switchClasses(element, class1, class2) {
  if (element.classList.contains(class1)) {
      element.classList.remove(class1);
      element.classList.add(class2);
  } else if (element.classList.contains(class2)) {
      element.classList.remove(class2);
      element.classList.add(class1);
  }
}


/***************************************************** */


const SCHEMA = {
    TableName: '',
    Entities:
        {
            VENDEE:  ["PK", "SK", "VendeeName", "City", "State", "DueDate", "Email", "MinLog", "ShortVendee", "VendeeName", "BizOwner", "CreatedAt", "UpdatedAt"],
            INVOICE: ["InvoiceID", "InvoiceServiceType", "InvoiceAmount", "InvoiceDescription", "InvoiceDueDate", "CreatedAt", "UpdatedAt"],
            PAYMENT: ["PaymentID", "InvoiceID", "PaymentAmount", "PaymentDate", "PaymentDescription", "CreatedAt", "UpdatedAt"],
            LICENCE: ["LicenceID", "LicenceStartDate", "LicenceEndDate", "LicenceDescription", "CreatedAt", "UpdatedAt"],
            // COUNTER: ["VENDEE", "INVOICE", "PAYMENT", "LICENCE"]
        }

}
const entityTypes = Object.keys(SCHEMA.Entities);
// const entityTypes = ["VENDEE", "INVOICE", "PAYMENT", "LICENCE", "COUNTER"];

function configureMarkup(){
    return;
    if ( isLoggedIn()) {
        hideEl('.sp-open');
        showEl('.sp-auth');
    }else{
        hideEl('.sp-auth');
        showEl('.sp-open');
        // showEl('#userLoggedOutWrap');

    }
    
}



function processTableData(resource, body, tblAttributes){
    // console.log('res:', resource, 'body:', body);

    const wr = document.getElementById('datawrap');
    const cr = document.getElementById('current_resource');
    // const uri = a.dataset.uri;
    // const resource = a.dataset.resource;
    let newbody;
    if( Array.isArray(body) ){
        console.log('yes its array');
        data = body;
    }else{
        data = body[resource];
    }
    console.log( 'datais:', data);
    // data = body[resource] || body;

    let columns;

    switch(resource){
        case 'vendees':
            columns = ["PK", "MinLog", "ShortVendee", "BizOwner", "VendeeName", "Email", "Telephone", "Address", "City", "State", "ContactName", "InstallDate", "LiveDate", "DueDate"];
            break;
        case 'rawvendees':
            columns = ["vendee_name", "short_vendee", "min_log", "email", "tech_email", "address1",	"address2", "bG9ja2Vk", "vversion", "LastUpdateTime", "tel"];
            break;
        
        }
    
    const html = object2table(data, columns, tblAttributes, {PK: createAnchor, VendeeName: createAnchor});
    wr.innerHTML = html;
    let newtbl = wr.querySelector('table');
    
    if(newtbl.id === 'vendees-table'){
        let rows = newtbl.querySelectorAll('tbody tr');
        [...rows].forEach(row => {
            let cells = row.querySelectorAll('td');
            if (cells[1].textContent.trim() !== "" && cells[2].textContent.trim() !== "") {
                row.classList.add('bg-success-100');
            }
        });
    }

    cr.innerHTML = resource + ' ('+data.length+')';
}

function createAnchor(colkey, celltxt, rowdata){
    let rowjson = JSON.stringify(rowdata);
    let a = `<a
    href="#"
    class="text-primary"
    data-te-toggle="modal"
    data-te-target="#modalWrap"
    data-te-callback="populateEditForm"
    data-te-title="${rowdata.VendeeName}"
    data-rowdata='${rowjson}'
    data-te-ripple-init
    data-te-ripple-color="light">
    ${celltxt}
  </a>`;
    return a;
}

async function processJoinData(data) {
    console.log('joindata is:', data);
    const rawvendees = data['rawvendees'];
    const vendees = data['vendees'];
 
    let html = '<table class="min-w-full text-left text-sm font-light">';
    
    // console.log(vendees, vendees);
    for (const rawvendee of rawvendees) {
        // if( ! trim(item1.MinLog) ) continue;
        
        let rowdata = {
            MinLog: rawvendee.min_log,
            ShortVendee: rawvendee.short_vendee,
            VendeeName: rawvendee.vendee_name,
            Email: rawvendee.tech_email,

        }
        let rowjson;
        // console.log(rowjson);
        
        let row2 = '';
        for (const vendee of vendees) {
            let rowbg = 'bg-warning-100';
            if (vendee.ShortVendee === rawvendee.short_vendee) {
                if(vendee.MinLog === rawvendee.min_log) rowbg = 'bg-success-100';
                // console.log('yeah', vendee);

                /*overwrite with submitted data*/
                rowdata.PK = vendee.PK,
                rowdata.BizOwner = vendee.BizOwner,
                rowdata.City = vendee.City,
                rowdata.State = vendee.State,


                // console.log('vendee: ', vendee);
                // rowjson = JSON.stringify(vendee);

                row2 = `<tr class="border-b ${rowbg} dark:border-neutral-500 dark:bg-neutral-700"><td colspan=7 class="whitespace-nowrap px-6 py-4">${vendee.PK} &bull; ${vendee.MinLog} &bull; ${vendee.ShortVendee} &bull; ${vendee.VendeeName} &bull; ${vendee.City} &bull; ${vendee.Email || ''}</td></tr>`; // +Add more columns as needed
            }
        }

        // console.log('rowdata:', rowdata);
        rowjson = JSON.stringify(rowdata);
        html += `<tr class="hover:bg-neutral-100">
            <td class="italic">SUBMITTED: </td>
            <td>${rawvendee.min_log || ''}</td>
            <td>${rawvendee.short_vendee || ''}</td>
            <td>${rawvendee.vendee_name || ''}</td>
            <td>${rawvendee.tech_email || ''}</td>
            <td>${dateToLocale('DD.MM.YYYY', rawvendee.LastUpdateTime)}</td>
            <td>
                <a
                    href="#"
                    class="text-primary"
                    data-te-toggle="modal"
                    data-te-target="#modalWrap"
                    data-te-callback="populateEditForm"
                    data-te-title="${rawvendee.vendee_name}"
                    data-te-body=""
                    data-rowdata='${rowjson}'
                    data-te-ripple-init
                    data-te-ripple-color="light">
                    LINK
                </a>
            </td>
            </tr>`; // Add more columns as needed
        
        html += row2;
    }

    
    html += '</table>';
    
    document.getElementById('datawrap').innerHTML = html;
    // return html;
  }

 
function buildVendeeCollectionPage(jsonData){
    
    const entitiesByType = {};
    let html = "";
    const wr = document.getElementById('collectionWrap'); 
    
    // console.log('COllWrap iS:', wr);
    // return;

    // Initialize arrays for each entity type
    entityTypes.forEach(type => {
        entitiesByType[type] = [];
    });
    


    // Iterate over the JSON data and separate objects by EntityType
    jsonData.forEach(item => {
        const entityType = item.EntityType;

        // Check if the EntityType is in the entityTypes array
        if (entityTypes.includes(entityType)) {
            entitiesByType[entityType].push(item);
        }
    });

    // console.log( entitiesByType );
 
   
    // return;
    let PK = entitiesByType['VENDEE'][0].PK;
    let currentVendee = entitiesByType['VENDEE'][0].VendeeName;
    entityTypes.forEach(type => {
        // entitiesByType[type] = [];
        let thisType = entitiesByType[type];
        // let entities = SCHEMA.Entities[type];
        
        
        html += `<div class="bg-neutral-100 hover:shadow-lg rounded-lg overflow-hidden mb-4">`;
        html += `<h3 class="flex justify-between border-b border-blue-300 text-lg font-medium px-4">
            <span class="text-left font-bold">${type}s</span>
            <a href="#" class="text-primary text-right text-sm" data-te-toggle="modal" data-te-target="#modalWrap" data-te-callback="populateEntityForm" data-te-title="Create New ${type}: ${currentVendee}" data-te-body="" data-rowdata='{"PK":"${PK}", "SK":"", "EntityType":"${type}"}' data-te-ripple-init data-te-ripple-color="light">
            Add ${type}</a>
            </h3>`;
        html += `<ul>`;
        
        if(wr){
       // console.log(tbl);
    //    document.getElementById('collectionWrap').innerHTML += tbl;
    //    wr.innerHTML = tbl;
    } else {
        console.log('no wrap!!!');
    }
    
    /* 
    return; 
    let tbl = object2table(thisType);
    html += tbl;
 */
         thisType.forEach(attrs => {
            // console.log('attrs:', attrs);
            html += `<li class="text-left">
                <div class="p-4 text-sm grid grid-cols-4">`;
                for(let attr in attrs){
                    let attrPhr, attrVal = attrs[attr];
                    

                    if(attr === 'InvoiceAmount'){
                        attrPhr = `<a href="#" class="text-primary" data-te-toggle="modal" data-te-target="#modalWrap" data-te-callback="populateEntityForm" data-te-title="Add Payment: ${currentVendee}" data-te-body="" data-rowdata='{"PK":"${PK}", "SK":"", "InvoiceID": "${attrs.SK}", "PaymentAmount": "${attrs.InvoiceAmount}", "EntityType":"PAYMENT"}' data-te-ripple-init data-te-ripple-color="light">
                         ${attrVal}</a>`;
                    }else if(attr === 'SK'){
                        attrPhr = `<a href="#" class="text-primary" data-te-toggle="modal" data-te-target="#modalWrap" data-te-callback="populateEntityForm" data-te-title="Edit ${type}: ${currentVendee}" data-te-body="" data-rowdata='${JSON.stringify(attrs)}' data-te-ripple-init data-te-ripple-color="light" title="Edit This Item">
                        ${attrVal}</a>`;
                    }else{
                        attrPhr = attrVal;
                    }

                    // let attrPhr = attr === 'SK' ? editLink : attrs[attr];


                   html+=  `<span class="">${attr}</span> <span class="font-semibold">${attrPhr}</span>`;
                }
                    
            html += `</diV>
            </li>`;
        }); 
        html += `</ul>`;
        html += `</div>`;
        
    });

if(wr) wr.innerHTML = html;
return;

}

function buildVendeeList(jsonData){
    const wr = document.getElementById('datawrap');
    let html = '<div id="listWrap" class="flex">';

    console.log("list jsondata data:", jsonData);
    let rows = jsonData.body;
    let ulhtml = `<div class="bg-gray-100 shadow-lg rounded-lg overflow-hidden w-1/3 md:max-w-lg">
    <div class="md:flex">
        <div class="w-full p-4">
            <ul>`;
    rows.forEach(row => {
        let locArr = [];
        if(row.City) locArr.push(row.City);
        if(row.State) locArr.push(row.State);

        row.Location = locArr.join(', ');

        // console.log("row:", row);
        ulhtml += `
        <li><a href="/vlist/${row.PK}" class="text-left flex justify-between items-center bg-white mt-2 p-2 hover:shadow-lg rounded cursor-pointer transition">
                <div class="flex ml-2">
                    <img class="hidden" src="/img/swiftpracticelogosmall.png" width="40">
                    <div class="flex flex-col ml-2"> <span class="font-medium text-black">${row.VendeeName}</span>
                        <span class="text-sm text-gray-400 truncate w-32">${row.Location}</span>
                    </div>
                </div>
                <div class="flex flex-col items-center"> <span class="text-gray-300">${row.BizOwner}</span>
                    <i class="fa fa-star text-green-400"></i>
                </div>
        </a></li>
            `;
    });
    ulhtml += `</ul>
            </div>
         </div>
        </div>`;

    html += ulhtml;
    html += '<div  class="w-2/3 p-4 bg-gray-100 shadow-lg rounded-lg overflow-hidden" id="collectionWrap"></div>';
    wr.innerHTML = html;




}

function activateDropdowns(){
  let trs = document.querySelectorAll('[data-dropdown-trigger]');
  for(let tr of trs){
    let targetid = tr.getAttribute('data-dropdown-target');
    let target = document.getElementById(targetid);

    const dropdown = new Dropdown(target, tr);

  }
}

function openHostedUI() {
    // window.open(COGNITO.login_url, "Cognito Hosted UI", "width=800,height=200");
  }

