//import { cachedDataVersionTag } from "v8";
import { forEach } from "lodash";
import A11yDialog from "../../libs/a11y-dialog";

function bs4HandleUploadEvent(e) {
  console.bs4log('ccdev 2', e);
  console.bs4log('ccdev 3',e.type,`${e.loaded} bytes transferred`);
  if(e.type=='progress')
  {
    console.bs4log('ccdev 6');
    var pc = (80* e.loaded / e.total)+10;
    console.bs4log('ccdev 8 pc: ', pc);
    //e.target.queueItem.querySelector('p[data-file-name]').innerHTML = ;
    console.bs4log(e.target);
    console.bs4log(e.target.queueItem);
    e.target.queueItem.querySelector('div.progress__bar').style.width = pc+'%';
    console.bs4log('ccdev 11 pc: ', pc);
  }
}
function bs4FormatBytes(bytes)
{
  var size = parseInt(bytes);
  var txt = size+" B";
  if(size>1024)
  { size=Math.round(size/1024,2);
    txt=size+" Kb";
    if(size>1024)
    { size=Math.round(size/1024,2);
      txt=size+" Mb";
      
    if(size>1024)
      { size=Math.round(size/1024,2);
        txt=size+" Gb";
        if(size>1024)
        { size=Math.round(size/1024,2);
          txt=size+" Tb";
        }
      }
    }
  }
  return txt;
}
function bs4CheckFileType(filename, accept)
{
  console.bs4log('ccdev 41, accept', accept);
 
  if(accept==null || accept=='')
    return true;

  var isvalid=false;
  var fext = '.'+filename.split('.').pop().toLowerCase();
  console.bs4log('ccdev 42, fext', '>'+fext+'<');
  // spit on spaces or commas
  var types = accept.split(/[\s,]+/);
  console.bs4log('ccdev 44, types', types);
  [...types].forEach((item, i) => {
    item = item.trim().toLowerCase();
    console.bs4log('ccdev 47 item, ', '>'+item+'<');
    if(fext==item)
        isvalid=true;
  });

  return isvalid;
}
function bs4AjaxFileItem(target, item, dir='', topdir='', accept='')
{   
    console.bs4log('ccdev 64 dza', target, item,dir,topdir,accept);
    if((topdir=='') || (topdir==null))
      topdir='images';
    if(target==null)
      target=document;
    const qItem = target.querySelector('#hiddenFileQueueItem').querySelector('.file-upload').cloneNode(true);

    qItem.querySelector('p[data-file-name]').innerHTML = item.name;
    qItem.querySelector('span[data-file-size]').innerHTML = bs4FormatBytes(item.size);

    target.querySelector('[data-role=file-queue]').insertAdjacentElement('afterbegin', qItem);

    if(!bs4CheckFileType(item.name, accept))
    { qItem.querySelector('p[data-file-name]').innerHTML = item.name+" <span class='file-error-msg'>Invalid FileType, cannot upload.</span>";
      return;
    }
    
    qItem.querySelector('div.progress__bar').style.width = '5%';
    
    const xhr = new XMLHttpRequest();
    xhr.queueItem = qItem;
    xhr.upload.queueItem = qItem;
    xhr.onload = function() {
        if (xhr.status === 200) {
            //console.bs4log('Ajax200:',  xhr.status, xhr.responseText);
            //alert('Ajax200: ', xhr.responseText);
            console.bs4log('ccdev 09', item);
            console.bs4log('ccdev 10', xhr.response);
            var resp = JSON.parse(xhr.response);

            console.bs4log('ccdev success, ', resp.success);
            if(resp.success=="1")
            { //xhr.queueItem.querySelector('p[data-file-name]').innerHTML = resp.original;
              xhr.queueItem.querySelector('p[data-file-name]').innerHTML = resp.optimised;
              xhr.queueItem.querySelector('div.progress__bar').style.width = '100%';


              
              // Add tick and completion state
            
              xhr.queueItem.setAttribute('data-state', 'complete');
              
              // Add this back in if needed
              //xhr.queueItem.querySelector('div.featured-icon').innerHTML = "<img src='"+resp.thumbnail+"' />"
              
              //fire a change on the directory selector to repopulate the images if they exist
              //var dir = document.getElementById('uploadDirectory').value;
              var libraryitems = target.querySelector('div[data-role=media-items]');
              //console.log('ccdev rt 102', libraryitems, topdir+'/'+dir );
              bs4RefreshThumbnails(libraryitems, topdir+'/'+dir );

              //refresh this image anywhere on the page
              //console.log('ccdev complete resp', resp);
              const rand = "?refresh=" + Math.random();
              const imgs = [resp.optimised, resp.original, resp.thumbnail];
              imgs.forEach((url) =>{
                  let match = 'img[src^="' + url + '"]';
                  // also match with %20 instead of spaces
                  let match2 = 'img[src^="' + url.replace(' ', '%20') + '"]';
                  
                  //console.log('ccdev url, match', url, match, match2);                
                  document.querySelectorAll(match).forEach((imgEle)=>{
                    //console.log('ccdev 123 replacing', imgEle);
                    imgEle.src = url + rand;
                  })
                  document.querySelectorAll(match2).forEach((imgEle)=>{
                    //console.log('ccdev 123 replacing', imgEle);
                    imgEle.src = url + rand;
                  })
              });

            } else
            {
              const elem = xhr.queueItem.querySelector('p[data-file-name]');
              elem.innerHTML = elem.innerHTML + "<span class='file-error-msg'>... Upload Failed, Please Try Again, "+resp.error+"</span>";
              xhr.queueItem.querySelector('div.progress__bar').style.width = '0%';
            }
        }
        else
        {
            bs4.log('AjaxFail 110:',  xhr.response)
            const elem = xhr.queueItem.querySelector('p[data-file-name]');
            if(elem!=null)
              elem.innerHTML = elem.innerHTML + "<span class='file-error-msg'>... Upload Failed, Please Try Again, "+resp.error+"</span>";
            xhr.queueItem.querySelector('div.progress__bar').style.width = '0%';
            xhr.queueItem.setAttribute('data-state', 'error');
            //alert('Request failed.  Returned status of ' + xhr.status);
        }            
    }
    
    var formData = new FormData();
    formData.append('dir', dir);
    formData.append('topdir', topdir);
    formData.append('file', item);

    const overswitch = target.querySelector('input#mediamanager-overwrite-switch');
    if(overswitch) {
      formData.append('overwrite', overswitch.checked);
    } else {
      formData.append('overwrite', false);
    }

    let model='';
    let fieldname='';
    try {
      var thumb = target.querySelector('div.media__sidebar img[data-role=sidebar-thumbnail]');
      model = thumb.getAttribute('data-img-model');
      fieldname = thumb.getAttribute('data-img-fieldname');

    } catch (error) {
      
    }
    bs4.log('ccdev 00150', model, fieldname);

    formData.append('model', model);
    formData.append('fieldname', fieldname);    
    
    xhr.open("POST", "/adminBS4/ajax/drop-file-upload", 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.addEventListener('loadstart', bs4HandleUploadEvent);
    //xhr.addEventListener('load', bs4HandleUploadEvent);
    xhr.addEventListener('loadend', bs4HandleUploadEvent);
    xhr.upload.addEventListener('progress', bs4HandleUploadEvent);
    xhr.addEventListener('error', bs4HandleUploadEvent);
    //xhr.addEventListener('abort', bs4HandleUploadEvent);

    xhr.timeout = 300000; // time in milliseconds
    
    xhr.send(formData);
}
function bs4RefreshThumbnails(target, dir)
{
  //if the target (the galley) exists refresh it
  //var libraryitems = document.querySelector('div[data-role=media-items]');
  //@TODO: front-end this realkly needs a busy spinner
  if(target!=null)
  {
    target.innerHTML = "<div style='text-align:center;font-size:200%;'>Loading...</div>";
  
    const xhr = new XMLHttpRequest();
    xhr.onload = function() {
        if (xhr.status === 200) {
          //console.bs4log('Ajax200:',  xhr.status, xhr.responseText);
          //alert('Ajax200: ', xhr.responseText);
          //document.getElementById("demo").innerHTML = this.responseText;
          //console.bs4log('ccdev 238', xhr);
          target.innerHTML = xhr.response;
          //bs4refreshImageEvents();
          } else
          {
            console.bs4log('AjaxFail 243:',  xhr.response)
          }
        }

    console.bs4log('ccdev 246 dir', dir);
    var formData = new FormData();
    formData.append('dir', dir);

    xhr.open("POST", "/adminBS4/ajax/media-getimages", 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.send(formData);
  }
}

function bs4ShowDropZone(event) {
  var dataItem = event.target.closest('[data-previous-value]');

  if(dataItem==null) dataItem = event.target;

  var prev = dataItem.getAttribute('data-previous-value');
  if(prev==null) prev='';

  var mediaModal =  event.target.closest('[data-a11y-dialog]');
  if(mediaModal==null) mediaModal=null;
  
  bs4.log('ccdev 267 mediaModal', mediaModal, event.target.value);

  if(event.target.value=="+") {
    bs4.log('ccdev 270',event.target, event.target.getAttribute('data-folder'));
    
    if(mediaModal != null)
        var modal = document.querySelector('[data-role=add-folder-modal]');
    else
        var modal = document.querySelector('[data-role=add-folder-modal]');

    bs4.log(modal)
    
    bs4.log('ccdev 274', 'modal', modal);
    modal.setAttribute('data-folder', event.target.getAttribute('data-folder') );
    
    // Instantiate a new A11yDialog module
    bs4.log('ccdev 231 mediaModal',mediaModal);
    modal.style.zIndex=990999;
    const dialog = new A11yDialog(modal);
    dialog.show();
    bs4.log('ccdev 235 mediaModal',mediaModal);
    modal.querySelector('[data-a11y-dialog-show]').click();
    bs4.log('ccdev 237 mediaModal',mediaModal);
    
  } else if(event.target.value=="")
  {
    if(mediaModal!=null)
        var dz = mediaModal.querySelector('.dropzone');
    else
        var dz = document.querySelector('.dropzone');
    
    dz.classList.add('sr-only');
    dz.setAttribute('data-disabled', true);    
    
  } else
  { 
    if(mediaModal!=null)
    {
      var dz = mediaModal.querySelector('.dropzone');
      dz.classList.remove('sr-only');
      dz.setAttribute('data-disabled', false);

      var topdir = event.target.getAttribute('data-folder');
      if(topdir==null || topdir=='')
      { var dz =  event.target.closest('[data-folder]');
        if(dz!=null)
          topdir = dz.getAttribute('data-folder');

        if(topdir==null || topdir=='')
          topdir='images';
      }

      var libraryitems = mediaModal.querySelector('div[data-role=media-items]');
      console.bs4log('ccdev rt 302', libraryitems,  topdir+'/'+event.target.value);

      bs4RefreshThumbnails(libraryitems, topdir+'/'+event.target.value);

    } else
    var dz = document.querySelector('.dropzone');
    dz.classList.remove('sr-only');
    dz.setAttribute('data-disabled', false);
    
    dataItem.setAttribute('data-previous-value', event.target.value);
  }
}
function bs4InitFileDrop()
{
    //ondrop="bs4MediaDrop(event);" ondragover="bs4MediaDragOver(event);"

    document.querySelectorAll('.dropzone').forEach(item => {
        item.addEventListener('drop', event => {

            event.preventDefault();
            console.bs4log('mediaDrop', event);

            //var dir = document.querySelector('select#uploadDirectory').value;
            var modal = event.target.closest('.modal__content');
            var selector = null;
            if(modal!=null)
            {   selector = modal.querySelector('select#uploadDirectory');
                if(selector==null)
                    selector = modal.querySelector('input[type="radio"]:checked');
            }
            if(selector==null)
                selector = document.querySelector('input[type="radio"]:checked');
            
            var dir = selector.value;

            console.bs4log('ccdev dz 172', dir);

            if((dir=="") || (dir=="+"))
            {  //alert("please select an upload directory");
               document.getElementById('warning-nofolder-modal').querySelector('[data-a11y-dialog-show]').click();
               return;
            }
            var accept = event.target.getAttribute('accept');
            if(accept==null || accept=='')
            { var dz =  event.target.closest('[accept]');
              if(dz!=null)
                accept = dz.getAttribute('accept');
            }
            var topdir = event.target.getAttribute('data-folder');
            if(topdir==null || topdir=='')
            { var dz =  event.target.closest('[data-folder]');
              if(dz!=null)
                topdir = dz.getAttribute('data-folder');
            }
            //console.bs4log('ccdev 192 accept', accept, topdir, event.target);

            var mediaModal =  event.target.closest('[data-a11y-dialog]');
            console.bs4log('ccdev 230aa dz', dir, topdir, accept, mediaModal);
            if (event.dataTransfer.items) {
                // Use DataTransferItemList interface to access the file(s)
                [...event.dataTransfer.items].forEach((item, i) => {
                  // If dropped items aren't files, reject them
                  if (item.kind === 'file') {
                    const file = item.getAsFile();
                    console.bs4log('ccdev 206', mediaModal, file, dir, topdir, accept);
                    bs4AjaxFileItem(mediaModal, file, dir, topdir, accept);
                  }
                });
              } else {
                // Use DataTransfer interface to access the file(s)
                [...event.dataTransfer.files].forEach((file, i) => {
                  console.bs4log(`… file[${i}].name = ${file.name}`);
                  console.bs4log('ccdev 213', mediaModal, file, dir, topdir, accept);
                  bs4AjaxFileItem(mediaModal, file, dir, topdir, accept);
                });
              }

        });

        item.addEventListener('dragover', event => {
            event.preventDefault();
        });
        item.addEventListener('click', event => {
          event.target.closest('div.dropzone').querySelector('input[type=file]').click();
        });

        item.querySelector('input[type=file]').addEventListener('change', event => {
          var mediaModal =  event.target.closest('[data-a11y-dialog]');

          if(mediaModal==null)
            var selector = document.querySelector('input[type="radio"]:checked')  
          else
            var selector=mediaModal.querySelector('select#uploadDirectory');

          var dir = selector.value;
          console.bs4log('ccdev 309', dir);

          if((dir=="") || (dir=="+"))
          {  alert("please select an upload directory"); //to be fair you should never see this
             //document.getElementById('warning-nofolder-modal').querySelector('[data-a11y-dialog-show]').click();
             return;
          }
          var accept = event.target.getAttribute('accept');
          if(accept==null || accept=='')
          { var dz =  event.target.closest('[accept]');
              if(dz!=null)
                accept = dz.getAttribute('accept');
          }
          var topdir = event.target.getAttribute('data-folder');
          if(topdir==null || topdir=='')
          { var dz =  event.target.closest('[data-folder]');
              if(dz!=null)
                topdir = dz.getAttribute('data-folder');
          }
          console.bs4log('ccdev 230bb dz', dir, topdir, accept);

          var files = event.target.files;
          console.bs4log('ccdev files selected', files.length);
          for(var i=0; i<files.length; i++)
          {
            console.bs4log('ccdev 252', mediaModal, files[i], dir, topdir, accept);
            bs4AjaxFileItem(mediaModal, files[i], dir, topdir, accept);
          }

        });
        
        //overwrite swicthes
        item.querySelectorAll('input[id="mediamanager-overwrite-switch"]').forEach((elemSwitch) => {
          console.log('ccdev 396 attaching switch', elemSwitch);
          elemSwitch.addEventListener('click', bs4StopPropogation);
        })
        item.querySelectorAll('label[for="mediamanager-overwrite-switch"]').forEach((eleLabel) => {
          console.log('ccdev 399 attaching label', eleLabel);
          eleLabel.addEventListener('click', bs4StopPropogation);
          //eleLabel.style.pointerEvents = 'auto'; // <-- this stops the actual switch from working
        })
    });

    document.querySelectorAll('select#uploadDirectory').forEach(item => {
      item.addEventListener('change', bs4ShowDropZone);
    });

}
const bs4StopPropogation = (event) => {
  console.log('ccdev 409 stopPropogation');
  event.stopImmediatePropagation();
  event.stopPropagation();
  console.log('ccdev 412 stopPropogation');
}

const bs4ClickCreateFolder = (event) => {
    console.bs4log('ccdev 303', 'click', event.target);
    var modal = event.target.closest('[aria-modal]');
    console.bs4log('ccdev 305', modal);
    
    var dname = modal.querySelector('input#dirname').value;
    var topdir = modal.getAttribute('data-folder');
    if((topdir==null) || topdir=='' || topdir=='null')
        topdir='images';

    var parent = modal.closest('[data-a11y-dialog=media-library-modal]');
    if(parent==null)
       parent = modal.closest('div.form-group');

    if(parent==null) //media rather than files
            parent = modal.closest('.page').querySelector('[data-a11y-dialog=media-library-modal]');
    bs4.log('ccdev 415 parent', parent);

    var selector=null;
    if(parent!=null)
      selector = parent.querySelector('select#uploadDirectory');
    bs4.log('ccdev 420 selector', selector);
    
    var mediaModel=null;
    if(selector!=null)
    { var mediaModal = selector.closest('[data-a11y-dialog]');
      console.bs4log('ccdev 380',mediaModal);
      var libraryitems = mediaModal.querySelector('div[data-role="media-items"]');
      console.bs4log('ccdev 382',libraryitems);
      libraryitems.innerHTML = "<div style='text-align:center;font-size:200%;'>Creating Directory...</div>";  
    }

    console.bs4log('ccdev 241 ', topdir, dname );          
    
    if(dname!='')
    { //const parser = new URL( window.location);
      //parser.searchParams.set('mkdir', dname);
      //window.location = parser.href;
      
      if(selector!=null)
        selector.querySelectorAll('option:not([value=""]):not([value="+"])').forEach(item => {
          item.remove();
        });
      else
      { document.querySelectorAll('div[data-type="folder-tag"]:not(.sr-only)').forEach(item => {
          item.remove();
        });
        var emptyItem = document.querySelector('div[data-type="folder-tag"].sr-only');

        var newItem = emptyItem.cloneNode(true);
            newItem.classList.remove('sr-only');
            newItem.querySelector('label span[data-label]').innerHTML = 'Creating Folder...';
            newItem.querySelector('input').value = '';
            document.querySelector('div[data-type="folder-tag"].sr-only')
                    .insertAdjacentElement('beforeBegin', newItem);
      }

      const xhr = new XMLHttpRequest();
      xhr.mydirname = dname;
      xhr.onload = function() {
        if (xhr.status === 200)
        {
          //console.bs4log('Ajax200:',  xhr.status, xhr.responseText);
          //alert('Ajax200: ', xhr.responseText);
          //document.getElementById("demo").innerHTML = this.responseText;
          bs4.log('ccdev 250', xhr.response);
          //{"2022-11-04-test":"2022-11-04-test","90210":"90210","Banners":"Banners","Grades":"Grades","People":"People"}
          
          document.querySelectorAll('div[data-type="folder-tag"]:not(.sr-only)').forEach(item => {
            item.remove();
          });
          
          var data = JSON.parse(xhr.response);
          bs4.log('ccdev 470 selector', selector);

          document.querySelectorAll('select#uploadDirectory').forEach(eachSelector =>{
            for(var i in data)
            { 
              var selected = (xhr.mydirname==i) ? 'selected' : '';
              eachSelector.insertAdjacentHTML("beforeend", `<option ${selected} value="${i}">${i}</option>`);
            }
          });
          
          for(var i in data)
          { bs4.log('ccdev 471', i);
            if(selector!=null)
            { var selected = (xhr.mydirname==i) ? 'selected' : '';
              selector.insertAdjacentHTML("beforeend", `<option ${selected} value="${i}">${i}</option>`);
            } else
            {
              var newItem = emptyItem.cloneNode(true);
              newItem.classList.remove('sr-only');
              newItem.querySelector('label span[data-label]').innerHTML = i;
              newItem.querySelector('input').value = i;
              var slug = i.toLowerCase().replace(' ','-');
              newItem.querySelector('input').setAttribute('id', 'bs4-upload-folder-'+slug);
              if(xhr.mydirname==i) {
                newItem.querySelector('input').checked = true;
              }
              newItem.querySelector('label').setAttribute('for', 'bs4-upload-folder-'+slug);

              document.querySelector('div[data-type="folder-tag"].sr-only')
                  .insertAdjacentElement('beforeBegin', newItem);
            }
          }
          if(selector!=null)
            selector.value = xhr.mydirname;
          
          console.bs4log('ccdev rt 357', libraryitems, topdir+'/'+dname );
          bs4RefreshThumbnails(libraryitems, topdir+'/'+dname);

          if(mediaModal!=null)
            mediaModal.querySelector('.dropzone').classList.remove('sr-only');
          else
            document.querySelector('.dropzone').classList.remove('sr-only');
            
        } else
        { console.bs4log('AjaxFail 253:',  xhr.response)
        }
      }

      var formData = new FormData();
      formData.append('mkdir', topdir+'/'+dname );
      xhr.open("POST", "/adminBS4/ajax/media-mkdir", 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.send(formData);
    }
};

/**
 * Set attributes on the file modal sidebar when a file item is clicked
 * 
 * @param {Object} event file item click event
 */

const bs4ClickMediaItem = (event) => {
    var item =  event.target.closest('div.media-library__item');
    var allMedia = event.target.closest('.media__library-items').querySelectorAll('.media-library__item[data-media-type=image]');
    var id = item.getAttribute('data-media-id');
    var filename = item.getAttribute('data-media-filename');
    if(filename==null)
      filename='';
    var src = item.querySelector('img').src;
    var dims = item.getAttribute('data-media-width');

    // Set selected state on item
    allMedia.forEach((media) => {
        const isSelected = media === item;
        media.setAttribute('data-selected', isSelected);
    });


    if(dims!='' && dims!=null)
        dims = ''+ dims + ' x ' + item.getAttribute('data-media-height');
    else
        dims='unknown';
    console.bs4log('ccdev 320 dims', dims);

    //var thumb = document.querySelector('img.media__sidebar-thumb');
    var thumb = document.querySelector('img[data-role=sidebar-thumbnail]');
    thumb.src = src;
    thumb.setAttribute('data-media-id', id);
    document.querySelector('p[data-role=sidebar-file-name]').innerHTML = filename.replace('.', '&#8203;.').replace('-', '&#8203;-').replace('_', '&#8203;_');
    document.querySelector('span[data-role=sidebar-file-dimensions]').innerHTML = dims;

    var placeholder = document.querySelector('[data-role=sidebar-placeholder]');
    thumb.classList.remove('sr-only');
    placeholder.classList.add('sr-only');

    console.bs4log('ccdev 311 ',);
}

/**
 * Set attributes on the file modal sidebar when a file item is clicked
 * 
 * @param {Object} event file item click event
 */

const bs4ClickFileItem = (event) => {
    // HTMLElements
    console.bs4log('ccdev 543');
    const file = event.target.closest('.media-library__item[data-media-type=file]');
    const sidebar = event.target.closest('.modal__window')?.querySelector('.media__sidebar');
    const allMedia = event.target.closest('.media__library-items').querySelectorAll('.media-library__item');
  
    // Check if the sidebar and file elements exist
    if (!sidebar || !file) return false;
  
    // File attributes
    const { name: fileName, size: fileSize, url: fileUrl } = file.dataset;
  
    // Set file attributes on the sidebar
    sidebar.dataset.name = fileName;
    sidebar.dataset.url = fileUrl;
    sidebar.dataset.size = fileSize;
    sidebar.querySelector('p[data-role=sidebar-file-name]').innerHTML = fileName;
    sidebar.querySelector('span[data-sidebar-file-size]').innerHTML = fileSize;
    sidebar.querySelector('[data-dialog-id="title"]').value = fileName;

    // Set selected state on item
    allMedia.forEach((media) => {
        const isSelected = media === file;
        media.setAttribute('data-selected', isSelected);
    });
}
  

/**
 * Adds a file tag to a tag list
 * 
 * @param {Object} event update media click event
 */

const bs4AddFile4Item = (event) => {
    const sidebar = event.target.closest('.media__sidebar');

    const filename = sidebar.dataset.name;
    const url = sidebar.dataset.url;
    const size = sidebar.dataset.size;
    const title = sidebar.querySelector('[data-dialog-id="title"]').value;

    console.log(`ccdev dz 623 This function bs4AddFile4Item has been called for: ${filename}`);

    // 90210

    let forname = sidebar.getAttribute('data-for');
    //console.log('ccdev dz 626 forname', forname)

    let dataTarget = document.getElementById(forname);
    //console.log('ccdev dz 627 dataTarget',dataTarget)

    let origValue =  dataTarget.value;
    //console.log('ccdev dz 682',origValue);
    
    let origValue2 = dataTarget.getAttribute('value');
    //console.log('ccdev dz 685',origValue2);

    let data = {};
    if ( (origValue2 != '{}' && origValue2 != '[]') && bs4.hasJsonStructure(origValue2)) {
      //if empty object no need to parse it use default
      try {
        data = JSON.parse(origValue2);
      } catch (error) {
        //console.error('Failed to parse JSON:', error);
        data = {};
      }
    }
    //console.log('ccdev 696 origValue2', origValue2);
    //console.log('ccdev 698 typeof data', typeof data);
    
    let obj = {};
    obj.filename = filename;
    obj.url = url;
    obj.title = title;
    
    //console.log('ccdev dz 708 obj', JSON.stringify(obj));

    try {
      data[filename] = obj; //was erroring because was using wrong index
    } catch (error) {
      //sometimes errors -- so try both ([] above should now work regardless)
      data.push(obj);
    }
    
    //console.log('ccdev dz 714 data', JSON.stringify(data));

    dataTarget.value  = JSON.stringify(data);
    dataTarget.setAttribute('value', JSON.stringify(data));
    //fire off a change event so that the JSON will bubble up
    var event = new Event('change', { 'bubbles': true });
    dataTarget.dispatchEvent(event);

    bs4.log('ccdev dz 722', dataTarget);

    let fileList = document.querySelector('div[data-tag-list="'+sidebar.getAttribute('data-for')+'"]');

    //in particular PHQ3 uses this to post process PSD files
    //bs4.log('ccdev dz 605,', (typeof bs4.DropZoneFileSelectCallback));
    if (typeof bs4.DropZoneFileSelectCallback == "function") { 
      //in your application trap to do some processing
      //bs4.DropZoneFileSelectCallback = (data, dataTarget, fileList) =>{ ... ... };
      bs4.DropZoneFileSelectCallback(data, dataTarget, fileList);
    }
    bs4.log('ccdev dz 612', fileList, data);

    updateVisibleTags(fileList, data);
}

/**
 * Updates the list of tags in a tag list
 * 
 * @param {HTMLElement} tagList tag list to be updated
 * @param {string} data JSON data from 
 */

const updateVisibleTags = (tagList, data) => {
    if (!tagList) return false;
  
    tagList.querySelectorAll('span:not(.display-none)').forEach(e => e.remove());
  
    const newTags = Object.values(data).map(property => `
      <span class="tag" data-name="${property.filename}">
        <span class="tag__label">${property.title}</span>
        <button class="tag__action" type="button" data-role="tag-dismiss" data-action="delete-file-tag">
          <svg class="icon" data-size="xs" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg" focusable="false" aria-hidden="true">
            <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"></path>
          </svg>
        </button>
      </span>`);
  
    tagList.insertAdjacentHTML('afterbegin', newTags.join(''));
};


/**
 * Deletes a file tag from a tag list
 * 
 * @param {Object} event dismiss tag click event 
 */

const bs4FileTagDelete = (event) => {
    event.preventDefault();
    console.log('ccdev dz 711 event', event);

    // HTMLElements 
    const tag = event.target.closest('.tag');
    const dataInput = event.target.closest('.form-group').querySelector('input[data-role="files-upload-hidden"]');
    const tagList = document.querySelector(`.tag-list[data-tag-list="${dataInput.getAttribute('id')}"]`);

    // Attributes
    const tagName = tag.getAttribute('data-name');
    
    let dataValue = dataInput.value;
    console.log('ccdev dz 722 value 1', dataValue);
    let dataValue2 = dataInput.getAttribute('value');
    console.log('ccdev dz 725 value 2', dataValue2);
    
    let data = {};
    if ((dataValue != '') && dataValue !== null) { 
        data = JSON.parse(dataInput.value);
    }
        
    if (tagName == null) {
        delete data['null']; //special case
    } else {
        delete data[tagName]; //doesn't always work... so
        try {
          data.forEach((value,idx) => {
            if(value.filename==tagName) {
              data.splice(idx, 1);
            }
          });
        } catch (error) {
          // no error
        }
    }
    
    dataInput.value = JSON.stringify(data);
    //fire off a change event so that the JSON will bubble up
    var event = new Event('change', { 'bubbles': true });
    dataInput.dispatchEvent(event);

    updateVisibleTags(tagList, data);
};
const bs4DeleteFileItem = (event) => {
  console.bs4log('ccdev 664 ', event.target.dataset.url);
  const modal = document.getElementById('file-confirm-delete-modal')
  if(modal!=null)
  {
    modal.querySelector('span[data-role="file-confirm-delete-filename"]').innerHTML = event.target.dataset.name;
    var btn = modal.querySelector('button.modal__yes');
    btn.setAttribute('data-name', event.target.dataset.name);
    btn.setAttribute('data-url', event.target.dataset.url);
    btn.setAttribute('data-for', event.target.closest('[data-for]').getAttribute('data-for'));
    // Instantiate a new A11yDialog module
    const dialog = new A11yDialog(modal)
    dialog.show();
  }
};
const bs4AjaxDeleteFileItem = (event) =>{
  console.bs4log('ccdev 675 bs4AjaxDeleteFileItem',event.target.dataset);

  var libfiles = document.querySelector(`div.media[data-for="${event.target.dataset.for}"][data-view="modal"] div[data-role="media-items"]`);
  libfiles.innerHTML = "<div style='text-align:center;font-size:200%;'>Deleting...</div>";

  const xhr = new XMLHttpRequest();
  xhr.onload = function() {
      if (xhr.status === 200) {
          //console.bs4log('Ajax200:',  xhr.status, xhr.responseText);
          //alert('Ajax200: ', xhr.responseText);
          var resp = JSON.parse(xhr.response);
          console.bs4log('ccdev 687 response', resp);
          
          //TODO: get target 90210a
          var target = document.querySelector(`div.media[data-for="${resp.for}"][data-view="modal"] div[data-role="media-items"]`);
          bs4RefreshThumbnails(target, resp.fulldir );
      }
      else
      {
          console.bs4log('AjaxFail 110:',  xhr.response)
          /*
          const elem = xhr.queueItem.querySelector('p[data-file-name]');
          elem.innerHTML = elem.innerHTML + "<span class='file-error-msg'>... Upload Failed, Please Try Again, "+resp.error+"</span>";
          xhr.queueItem.querySelector('div.progress__bar').style.width = '0%';
          xhr.queueItem.setAttribute('data-state', 'error');
          //alert('Request failed.  Returned status of ' + xhr.status);
          */
      }            
  }
  
  var formData = new FormData();
  formData.append('url', event.target.dataset.url);
  formData.append('for', event.target.dataset.for);
  xhr.open("POST", "/adminBS4/ajax/delete-file-url", true);
  xhr.setRequestHeader('X-CSRF-TOKEN', document.querySelector('meta[name="csrf-token"]').content);
  xhr.send(formData);
};

document.addEventListener('DOMContentLoaded', () => {
    bs4InitFileDrop();

    document.addEventListener('click', (event) => {
      const target = event.target;
      //bs4.log('ccdev 576 debug', event);

      if (target.matches('.media-library__item[data-media-type=image]') || target.matches('img.media-library__item-preview')) {
        bs4ClickMediaItem(event);
      } else if(target.matches('#file-confirm-delete-modal button.modal__yes')){
        bs4AjaxDeleteFileItem(event);
      } else if(target.matches('[data-action="media-libraray-delete-item"]')){
        bs4DeleteFileItem(event);
      } else if (target.matches('.media-library__item[data-media-type=file]')) {
        bs4ClickFileItem(event);
      } else if (target.matches('[data-a11y-dialog-hide="save-file"]')) {
        bs4AddFile4Item(event);
      } else if (target.matches('[name="media-upload-folder"]')) {
        bs4ShowDropZone(event);
      } else if (target.matches('[data-action="delete-file-tag"]')) {
        bs4FileTagDelete(event);
      } else if (target.matches('[data-role=add-folder-modal] .modal__yes')) {
        bs4ClickCreateFolder(event);
      } //else bs4.log('ccdev 744 - lick not trapped in dropzone');

    });
});