{% load buttons %}
{% load i18n %}
{% load helpers %}
{% load static %}
{% load form_helpers %}

<div class=" show {% if request.GET.tab == 'netbox_to_slurpit' %}active{% endif %}">
    {% if appliance_type != 'cloud' %}
      <a name="sync"  class="btn btn-sm btn-orange my-2" href="{% url 'plugins:slurpit_netbox:data_mapping_list' %}?sync=true{% if request.GET %}&{{ request.GET.urlencode }}{% endif %}">
          <i class="mdi mdi-sync"></i> {% trans "Sync" %}
      </a>
    {% endif %}
    <div class="row mb-3">
      <div class="col col-md-6">
        <div class="card">
          
          <div class="card-header">
              <h6>Sync your NetBox devices to Slurp'it</h6>
              <span>
                In case you already have a filled NetBox system, and you want to sync those to Slurp'it to start collecting data then this is the page you are looking for.
                Below on the left you see the required attributes for in Slurp'it and on the right you can map those against your data from NetBox. If you need more information we can advise you to <a href="https://learning.slurpit.io/courses/offers/783fcc2c-f0f8-4a41-bc7c-64f1d03e43e8" target="_BLANK">
                click here</a> for our online course.
              </span>
          </div>
        </div>
      </div>
    </div>
    <div class="row mb-3">
        
        <div class="col col-md-6">
            <form action="" method="post" id="mapping-form" class="form form-horizontal mb-3">
                <div class="card">
                
                  <div class="card-header" style="display:flex;justify-content: space-between;">
                      <h5>Mapping Fields</h5>
                      <div class="action">
                        
                        <a class="btn btn-purple btn-sm px-3" data-bs-toggle="modal" data-bs-target="#testMapModal">
                          {% trans "Test" %}
                        </a>
                        <button class="btn btn-blue btn-sm px-3">
                            {% trans "Save" %}
                        </button>
                      </div>
                  </div>
                  <div class="card-body">
                    {% csrf_token %}
                    <input type="hidden" name="action" value="save" id="actionInput" />
                    {% for choice_item in form %}
                      <div class="d-flex map-item">
                        <input type="checkbox" name="pk" value="{{ choice_item.choice }}"/>
                        <input type="hidden" name="source_field" value="{{ choice_item.choice }}"/>
                        {% render_form choice_item.form %}
                      </div>
                    {% endfor %}
                  </div>
                  <div class="card-footer">
                    <button type="button" class="btn btn-sm btn-success" data-bs-toggle="modal" data-bs-target="#addMapModal">
                        <i class="mdi mdi-plus-thick"></i> Add
                    </button>
                    <button id="delete-btn" class="btn btn-danger btn-sm">
                        <i class="mdi mdi-trash-can-outline" aria-hidden="true"></i> Delete Selected
                    </button>
                  </div>
                </div>
              </form>
        </div>
    </div>
</div>

<div class="modal fade" tabindex="-1" id="addMapModal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">

      <!-- Modal Header -->
      <div class="modal-header">
        <h4 class="modal-title">Create a mapping</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form  method="post">
          {% csrf_token %}
          <div class="modal-body">
            {% render_form new_form %}
          </div>
  
          <!-- Modal Footer -->
          <div class="modal-footer">
              <button type="submit" class="btn btn-outline-primary" id="add_btn" >{% trans "Add" %}</button>
              <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
          </div>
      </form>
      <!-- Modal Body -->
      
    </div>
  </div>
</div>

<div class="modal fade" tabindex="-1" id="testMapModal">
  <div class="modal-dialog modal-lg">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Test device mapping</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <form  method="post">
          {% csrf_token %}
          <div class="modal-body">
            <div class="device_form" style="display:flex;justify-content: space-between; margin-bottom: 15px;">
              <div class="" style="width: 60%;">{% render_form device_form %}</div>
              {% if appliance_type != 'cloud' %}
                <a class="btn btn-outline-primary btn-sm" style="height:35px;width:100px;" id="push_btn" >{% trans "Push" %}</a>
              {% endif %}
            </div>
            
            <textarea id="payload-result" name="payload-result" cols="40" rows="10" class=" form-control mb-2" placeholder="Payload Result" id="payload-result" style="height: 200px;"></textarea>
            {% if appliance_type != 'cloud' %}
              <textarea id="push-result" name="push-result" cols="40" rows="10" class=" form-control" placeholder="Push Result" id="push-result" style="height: 100px;"></textarea>
            {% endif %}
          </div>
  
      </form>
      <!-- Modal Body -->
      
    </div>
  </div>
</div>

<style>
  .map-item {
    width: 100% !important;
    gap: 100px;
  }
  .map-item .mb-3 {
    margin-bottom: 0px !important;
    width: 100% !important;
  }
  html[data-netbox-color-mode=dark] .mb-3 {
    margin-bottom: 0px !important;
  }
  .device_form label.text-lg-end {
    text-align: left !important;
    width: 75px !important;
  }
</style>

<script>
  var delElement = document.getElementById('delete-btn');
  var form = document.getElementById('mapping-form');
  var actionInput = document.getElementById('actionInput');
  var payloadResultTextarea = document.getElementById('payload-result');
  var pushResultTextarea = document.getElementById('push-result');

  delElement.addEventListener('click', function(event) {
    const checkboxes = document.querySelectorAll('input[name="pk"]');
    
    // Check if all checkboxes are unchecked
    const allUnchecked = Array.from(checkboxes).every(checkbox => !checkbox.checked);

    actionInput.value = "delete";
    form.submit()
    event.preventDefault()
  });


  var deviceElement = document.querySelector('select[name="device"]');
  var csrfToken = document.querySelector('input[name="csrfmiddlewaretoken"]').value;

    // Then, add an event listener for the 'change' event.
  deviceElement.addEventListener('change', function(event) {
      var device_id = this.value; // or event.target.value
      var data = new URLSearchParams();
      data.append('csrfmiddlewaretoken', csrfToken);
      data.append('device_id', device_id);
      
      fetch('/plugins/slurpit/data_mapping/?tab=netbox_to_slurpit', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: data
      }).then(function(response) {
        return response.json();
      }).then(function(res){
        const deviceRequestBody = JSON.stringify(res, null, 4); 
        payloadResultTextarea.value = deviceRequestBody;

      }).catch(function(error) {

      });
  });

  var pushButton = document.getElementById('push_btn');
  
  pushButton.addEventListener('click', function(event) {
    var device_id = (deviceElement.value == undefined ) ? "": deviceElement.value; // or event.target.value
    var data = new URLSearchParams();
    data.append('csrfmiddlewaretoken', csrfToken);
    data.append('device_id', device_id);
    data.append('test', 'test')

    fetch('/plugins/slurpit/data_mapping/?tab=netbox_to_slurpit', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      body: data
    }).then(function(response) {
      return response.json();
    }).then(function(res){
      const deviceRequestBody = JSON.stringify(res, null, 4); 
      pushResultTextarea.value = deviceRequestBody;

    }).catch(function(error) {

    });
  });
</script>