let layerCounter = 1;
const screenArea = document.querySelector('.screen');
let preview;




function createLayer(type) {

  switch (type) {

    case 'date':
      var dateNode = document.createElement("p");
      dateNode.setAttribute("id", `layer${layerCounter}-date`);
      dateNode.setAttribute("class", "dragable date editable");
      document.querySelector('.screen').appendChild(dateNode);
      AMIB.showPDate(`layer${layerCounter}-date`);
      layersCounterHandler('+');
      break


    case 'time':
      document.querySelector('#layer1-time').classList.replace('hideClock', 'showClock')
      setTimeout(startTime, 500);
      document.querySelector('#layer2-time').classList.replace('hideClock', 'showClock')

      // var dateNode = document.createElement("textarea");
      // dateNode.setAttribute("id", "layer"+layerCounter+'-time');
      // dateNode.setAttribute("class", "draggable resize time");
      // document.querySelector('.screen').appendChild(dateNode);
      // digitalClockId= "layer"+layerCounter+'-time'; 

      // startTime()
      // ++layerCounter;
      break


    // case 'iFrame':
    //   var frameNode = document.createElement("iframe");
    //   frameNode.setAttribute("id", `layer${layerCounter}-iFrame`);
    //   frameNode.setAttribute("class", "resize-drag iFrame");
    //   frameNode.setAttribute('src', 'http://opticalfiberco.com/')
    //   // var frameNode = document.createElement("p");
    //   // frameNode.innerText = 'ویرایش فریم'
    //   // frameNode.appendChild(frameNode);
    //   document.querySelector('.screen').appendChild(frameNode);
    //   ++layerCounter;
    //   break;
  }

}







// source switcher/graber component
// return the source (source/path) of source switcher
var selectedSource;
var userEntredPath;
let elem
let layerType
$('.source-switcher input').on('click', function () {

  elem = this.closest('.source-switcher')
  preview = elem.previousElementSibling


  function runPreview() {
    preview.innerHTML = ""

    if (preview.classList.contains('single-video-preview')) {
      preview.appendChild(createSingleVideoLayer())
      return selectedSource;

    } else if (preview.classList.contains('single-image-preview')) {
      preview.appendChild(createSingleImageLayer())
      return selectedSource;
    }
  }








  if (this.classList.contains('from-server')) {
    let selector = elem.nextElementSibling.childNodes[1]
    // show/hide the selector/input bar
    elem.nextElementSibling.style.display = 'block';
    selector.parentNode.nextElementSibling.style.display = 'none';


    selectedSource = selector.options[selector.selectedIndex].text;
    // grab source that user selected(from selector)
    selectedSourceGraber = function () {
      selectedSource = selector.options[selector.selectedIndex].text;

      runPreview()
      return selectedSource
    }

    // change listener for selector
    $(selector).on('change', function () {
      selectedSourceGraber()

    })

    runPreview()
    return selectedSourceGraber;

  } else if (this.classList.contains('by-path')) {
    // console.log('this',this.classList.contains('by-path'))
    // show/hide the input/selector bar
    elem.nextElementSibling.nextElementSibling.style.display = 'block';
    elem.nextElementSibling.style.display = 'none';

    // grab source that user added(from input)
    userEntredPath = elem.nextElementSibling.nextElementSibling.childNodes[1]
    selectedSource = userEntredPath.value

    $(userEntredPath).on('input', function () {
      selectedSource = this.value
      runPreview()
      return selectedSource;
    })

    runPreview()
    return selectedSource;
  }


})

// CreateLayer Single Image 
function createSingleImageLayer() {

  let imageNode = document.createElement("img");
  imageNode.setAttribute("id", `layer${layerCounter}-image`);
  imageNode.style = "transform': translate(23.9vw, 8.6vh"
  //imageNode.setAttribute('onmousedown',' selectClicked'+'('+'imageFullMark'+')')
  /* Binding image Source*/
  imageNode.setAttribute("src", selectedSource);
  return imageNode;
}

// CreateLayer Single Video Layer
function createSingleVideoLayer() {

  // console.log('single video src:', selectedSource)
  let videoNode = document.createElement("video");

  videoNode.setAttribute("id", `layer${layerCounter}-video`);
  videoNode.setAttribute('autoplay', 'true');
  videoNode.setAttribute('loop', 'true');

  /* Binding Video Source*/
  let videoSource = document.createElement("source");
  videoSource.setAttribute("src", selectedSource);
  videoSource.setAttribute("id", `video${layerCounter}`);

  videoNode.appendChild(videoSource);
  return videoNode;
}



$('.add-single-video-btn').on('click', function () {
  let videoLayer = createSingleVideoLayer()

  let videoWidth = document.querySelector('.single-video-width').value;
  let videoHeight = document.querySelector('.single-video-height').value;
  videoLayer.style.width = videoWidth + "%";
  videoLayer.style.height = videoHeight + "%";

  videoLayer.setAttribute("class", "resize-drag video");
  screenArea.appendChild(videoLayer);

  layersCounterHandler('+')

  clearPreview()
})



$('.add-single-image-btn').on('click', function () {

  let imageLayer = createSingleImageLayer()

  let imageWidth = document.querySelector('.single-image-width').value;
  let imageHeight = document.querySelector('.single-image-height').value;
  imageLayer.style.width = imageWidth + "%";
  imageLayer.style.height = imageHeight + "%";


  imageLayer.setAttribute("class", "resize-drag image");
  screenArea.appendChild(imageLayer);

  layersCounterHandler('+')
  console.log('add-single-image-btn ', layerCounter)
  clearPreview()
})



function clearPreview() {
  if (preview != undefined)
    preview.innerHTML = '';
}



//Select and Delete layer
var activeLayerId;
// select active layer
window.onclick = e => {
  activeLayerId = e.target.id;
}
// delete layer by delete key
document.addEventListener('keydown', function (e) {
  if (e.key === 'Delete') {

    if (activeLayerId.includes('time')) {

      document.querySelector('#layer1-time').classList.replace('showClock', 'hideClock')
      document.querySelector('#layer2-time').classList.replace('showClock', 'hideClock')
      // document.querySelector('.timeAttr').classList.replace('show', 'hidden');

      layersCounterHandler('-');


    } else if (activeLayerId.includes('layer')) {
      document.getElementById(activeLayerId).remove();

      layersCounterHandler('-');

    } else if (activeLayerId.includes('multiVideo')) {
      multiVideoReset()
      document.getElementById(activeLayerId).remove();
      console.log('mlti deleted');
      document.getElementById('addVideoBtn').setAttribute('data-target', '#multiVideo');

      layersCounterHandler('-');

    }

    console.log(activeLayerId)

  }
})





// Do somthing on modal open/close
// $('#modal-reserve').on('shown.bs.modal', function () {

// });
$('#single-video').on('hidden.bs.modal', function () {
  // console.log('modal close')
  clearPreview()

});
$('#modal-single-image').on('hidden.bs.modal', function () {
  // console.log('modal close')
  clearPreview()
});
$('#multiVideo').on('hidden.bs.modal', function () {
  document.querySelector('.mlt-video-preview').innerHTML = ""
  // document.getElementById('addMultiVideo').setAttribute('disabled','true');

});
$('#multiVideo').on('shown.bs.modal', function () {
  let newMltVideoLayer = document.createElement('video');
  newMltVideoLayer.setAttribute('id', 'multiVideoLayer');
  // newMltVideoLayer.setAttribute('id', `layer${layerCounter}-multiVideo`);


  document.querySelector('.mlt-video-preview').appendChild(newMltVideoLayer)
});


let contentEntered
document.querySelector('.add-content-btn').addEventListener('click', function () {

  contentEntered = CKEDITOR.instances.editor2.getData();
  // console.log('editor1',$('#editor1').val()) 



  let contentNodeEditor = document.createElement("div");
  contentNodeEditor.setAttribute("id", `layer${layerCounter}-content`);
  contentNodeEditor.setAttribute("class", "editable resize-drag contentArea");

  // let textNode = document.createElement("p");
  contentNodeEditor.innerHTML = contentEntered
  // textNodeEditor.appendChild(textNode);
  document.querySelector('.screen').appendChild(contentNodeEditor);
  layersCounterHandler('+');


})


// increase/decrease layer counter 
function layersCounterHandler(operator) {
  if (operator == '+') {
    console.log('layerCounter', layerCounter)
    ++layerCounter
    console.log('layerCounter after +', layerCounter)
  } else if (operator == '-') {
    console.log('layerCounter', layerCounter)
    --layerCounter
    console.log('layerCounter after -', layerCounter)
  }

}

// $('.size-input').click(function () {

//   console.log($('.size-input').not(this))

// })







