import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  
  connect() {
    this.url = document.getElementById('drawer').getAttribute('data-url')
    this.token = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
  }

  // Toggle node children in drawer
  toggle_children(event) {
    const node = this.element.closest('.node-row');
    node.classList.toggle('closed');

    // Already loaded
    if (node.parentNode.classList.contains('loaded')) {      
      
      fetch(this.url, {
        method: 'PATCH',
        headers: {
          'X-CSRF-Token': this.token,
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
         id: node.parentNode.dataset.id,
         expanded: !node.classList.contains('closed')          
        })
      }).then((response) => {
        // console.info('resolved', response)
      }).catch((err) => {
        console.info('rejected', err)
      })

      event.preventDefault();
    
    } else {
      node.parentNode.classList.add('loaded')
    }


  }

  // Mark current node in drawer  
  set_current(event) {

    // Remove old current
    var node = document.querySelector("#drawer .current")
    if (node) {
      node.classList.remove('current');
    }

    // Add new current
    node =  document.getElementById(`node_${event.params['id']}`)
    if (node) {
      node.classList.add('current')
    }
  }

}
