//import A11yDialog from 'a11y-dialog';
import A11yDialog from "../../libs/a11y-dialog";
import DeletePostItem from '../modal/delete-post-item';

function bs4ChangeAddress(event)
{
    bs4.log('ccdev genedit 4', event.target.value);
    if(event.target.value=-1)
    {
        event.target.value=0;

        const addAddressModal = event.target.closest('.form-group').querySelector('[aria-modal]');

        bs4.log('ccdev gened 11', event.target.closest('.form-group'));
        bs4.log('ccdev gened 12', event.target.closest('.form-group').querySelector('[aria-modal]'));

        if(addAddressModal!=null)
        { const dialog = new A11yDialog(addAddressModal);
          bs4.log('ccdev genedit 16');
        
          dialog.on('hide', function (element, event) {
            event.preventDefault();
        
            //@TODO: change this to detect OK button btn-primary ?
            bs4.log('ccdev gen 15 hide', event.target.matches('[data-action="delete-block"]'));
            if(event.target.matches('[data-action="delete-block"]'))
            {
                //@TODO: add code to save new address (Ajax call, add to order and add to drop down)
            }
          });

          bs4.log('ccdev genedit 26');
          dialog.show();
        }
        
    } else
    { //a new address was selected
      //now put it into the json field
      //yes no dialog to confirm apply address to order
      

    }
    
}

function bs4SelectSearch(event)
{
  bs4DoIndexSearch(event);  
}
function bs4KeyUpSearch(event)
{
  if(event.key=='Enter')
  { //enter key so do search now no waiting
    bs4DoIndexSearch(event);
    return;
  }

  //ignore keypresses of meta shift keys etc
  if((event.keyCode<=32) && (event.key!='Delete') && (event.key!='Baskspace') 
         || event.key=="Meta" || event.key=="Shift" || event.key=="Constrol")
  { //for these conditions don't do a search
    return;
  }

  var txt = event.target.value.trim();
  bs4.log('ccdev 52',event);

  if(txt!='')
  { //wait to see if the user is still typing things
    setTimeout(function(target, event, txt)
    { var newtxt = target.value;
      if(txt==newtxt)
      { //text has not changed after the timeout, so stopped typing
        //do your action, such as search()
        bs4DoIndexSearch(event);
      }
    },1250, event.target, event, txt);
  }
}
function bs4DoIndexSearch(event, datafields={})
{
  bs4.bell(0.1, 830.6, 0.4);

  var moduleContainer = event.target.closest('div[data-role="module-index-container"]');
  //inputs and selects
  bs4ReloadModuleIndex(moduleContainer, datafields);
}
function bs4ReloadModuleIndex(moduleContainer, datafields={})
{
  bs4.log('ccdev 090', datafields);

  if(moduleContainer!=null)
    var url = moduleContainer.dataset.href;
  else
  { var url = document.querySelector('div[data-ajax-href]').getAttribute('data-ajax-href');
  }
  bs4LoadModuleIndexUrl(moduleContainer, url, datafields);
}

function bs4LoadModuleIndexUrl(moduleContainer, url, datafields={})
{
    bs4.log('ccdev 102', datafields);
  
    if(moduleContainer==null)
    {
      moduleContainer = document.querySelector('div[data-role="main-module-container"]');
      var tableName ='';
    } else
    { var tableName = moduleContainer.dataset.module;
    }
    var tableDiv = moduleContainer.querySelector('[data-role="index-table-container"]');

    const placeholder = moduleContainer.querySelector('[data-role=table-placeholder]');
    
    tableDiv.innerHTML = '';
    placeholder.style.display = null;

    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        bs4.log('xhr.status',xhr.status, (xhr.status==200));
        if (xhr.status == 200) {
          //bs4.log('ccdev 119 xhr', xhr.response);
          tableDiv.innerHTML = xhr.response;
          placeholder.style.display = 'none';

          //re-attach a11y dialog events
          DeletePostItem();

        } else 
        {
          tableDiv.innerHTML = xhr.responseText;
          placeholder.style.display = 'none';
          bs4.log('ccdev 123 xhr error', xhr, xhr.responseText);
        }
    };    
    var formData = new FormData();

    moduleContainer.querySelectorAll('[data-role=module-index-search]').forEach(item => {
      bs4.log('ccdev 123 data',item.getAttribute('data-field-name'), item.value);
      if(item.value!='')
          formData.append(item.getAttribute('data-field-name'), item.value);
    });
    moduleContainer.querySelectorAll('[data-role=index-search]').forEach(item => {
        bs4.log('ccdev 127 data',item.getAttribute('data-field-name'), item.value);
        formData.append(item.getAttribute('data-field-name'), item.value);
    });

    //extra datafields (sorting info)
    for (const key of Object.keys(datafields)) {
	      bs4.log(`ccdev 145 ${key} = ${datafields[key]}`)
        formData.append(key, datafields[key]);
    }

    xhr.open("POST", url, true);

    //xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);

    xhr.timeout = 300000; // time in milliseconds
    bs4.log('ccdev 151 send', url, formData);
    xhr.send(formData);
  }
  function bs4PaginationClick(event)
  {
      event.preventDefault();
      bs4.log('ccdev 146 pagination click');
      
      var moduleContainer = event.target.closest('div[data-role="module-index-container"]');
      var url = event.target.href;
      bs4LoadModuleIndexUrl(moduleContainer, url);
  }

  function bs4ResetSearch(event)
  {
    bs4.bell(0.1, 830.6, 0.4);
    var moduleContainer = event.target.closest('div[data-role="module-index-container"]');
    if(moduleContainer==null)
    {
      //idle implementation, reload the page without a query
      window.location = window.location.pathname;
    } else
    {
      //its inside an editor so reload with ajax
      bs4ReloadModuleIndex(moduleContainer);
      //@TODO, reset GUI filters
    }
  }

/**
 * 
 * @param {*} event 
 */
const bs4ClickSort = (event) => {
    var data={};
    data.bs4field = event.target.getAttribute('data-sort-field');
    data.bs4sort = event.target.getAttribute('data-sort-order');
    bs4DoIndexSearch(event, data);
}

const bs4InputInvalid = (event) =>{
  const tab = event.target.closest('div.tabs__panel');
  if(tab!=null)
  {
    //console.log('ccdev 201 input', event.target)
    //const tabButton = 
    document.querySelector(`button[aria-controls=${tab.id}]`).click();
  }
};

const bs4InitTabbedVerification = () => {

  document.querySelectorAll('form[data-class] input').forEach( element =>{
    element.addEventListener('invalid',bs4InputInvalid);
  });

  document.querySelectorAll('form[data-class] select').forEach( element =>{
    element.addEventListener('invalid',bs4InputInvalid);
  });

  document.querySelectorAll('form[data-class] textarea').forEach( element =>{
    element.addEventListener('invalid',bs4InputInvalid);
  });
  
};

// function bs4ClickSortDesc(event)
// {
//   var fieldname=event.target.getAttribute('data-field-name');
//   bs4DoIndexSearch(event, null, "&bs4field="+fieldname+"&bs4sort=desc");
// }

//document.addEventListener('DOMContentLoaded', () => {
bs4.ready( () => {
    
    bs4InitTabbedVerification();

    document.querySelectorAll('select[bs4address]').forEach(item => {
        item.addEventListener('change', bs4ChangeAddress);
    });

    document.querySelectorAll("input#indexSearch").forEach(item => {
      item.addEventListener('keyup', bs4KeyUpSearch);
    });

    document.querySelectorAll("[data-role=index-search]").forEach(item => {
      //inputs and selectes
      item.addEventListener('change', bs4SelectSearch);
    });

    document.querySelectorAll('[data-role="index-search-reset"]').forEach(item => {
      //inputs and selectes
      item.addEventListener('click', bs4ResetSearch);
    });

    // now done with matches onn the document as can be reloaded with ajax
    // document.querySelectorAll("button[data-role=sort-listing]").forEach(item => {
    //   item.addEventListener('click', bs4ClickSort);
    // });

    document.addEventListener('click', (event) => {
      //pagination items can be loaded via ajax
      if( event.target.matches('div[data-role="module-index-container"] li[data-type="page"] a[href]') 
          || event.target.matches('div[data-role="module-index-container"] li[data-type="previous"] a[href]') 
          || event.target.matches('div[data-role="module-index-container"] li[data-type="next"] a[href]') 
          || event.target.matches('div[data-role="main-module-container"] li[data-type="page"] a[href]') 
          || event.target.matches('div[data-role="main-module-container"] li[data-type="previous"] a[href]') 
          || event.target.matches('div[data-role="main-module-container"] li[data-type="next"] a[href]') 
      )
      {    bs4PaginationClick(event);
      } else if(event.target.matches('button[data-role=sort-listing]'))
      {
          bs4ClickSort(event);
      }
      //else bs4.log('ccdev 015 - lick not trapped in geneditor');
    });

    //find modules in tabs and load then with ajax
    document.querySelectorAll('div[data-role="module-index-container"]')
      .forEach((element)=>{
      bs4ReloadModuleIndex(element);
    });

    /* this does lla of the  index tables includinn g the main one - bu tthe main one is loaded in the inital blade
    document.querySelectorAll('div[data-role="index-table-container"]')
        .forEach((element)=>{

          var moduleContainer = element.closest('div[data-role="module-index-container"]');
          bs4ReloadModuleIndex(moduleContainer);
        });
    */

    //force the search box to gain focus with cursor at end
    var el = document.getElementById('indexSearch');
    if(el!=null)
    {
      el.focus()
      if (typeof el.selectionStart == "number") {
          el.selectionStart = el.selectionEnd = el.value.length;
      } else if (typeof el.createTextRange != "undefined") {           
          var range = el.createTextRange();
          range.collapse(false);
          range.select();
      }
    }
});