{% extends 'base/base.html' %}
{% block start %}

<style>
  .bundle-link-disabled {
    pointer-events: none;
    cursor: not-allowed;
    opacity: 0.5;
  }
</style>


<section class="main_content dashboard_part default_content">

<div class="main_content_iner ">
<div class="container-fluid p-0">
<div class="row ">
<div class="col-lg-12">
<div class="single_element">
<div class="quick_activity">
<div class="row">
<div class="col-12">
<div class="quick_activity_wrap">
<!-- <h1>Welcome, {{request.user}}</h1> -->
<!-- <form method="post">
  {% csrf_token %}
  <select name="api_dropdown" id="apiDropdown">
      <option value="WEEK">Week</option>
      <option value="MONTH">Month</option>
  </select>
</form> -->
<!-- <p id="target-paragraph"></p> -->
<a href="{% url 'article_details' %}" class="bundle-link-disabled"><div class="single_quick_activity">
<div class="count_content">
  <div>
    <div class="hover-element">
      <p style="display: inline;font-size: 1rem;">Article</p>
      <p style="display: inline;font-size: 0.5rem;">Month</p>
      <img style="display: inline;opacity:0.3;height: 15px;width: 15px;float: right;vertical-align: middle;" src="/static/img/interrogation.png" alt="Logo">
  </div>
  </div>
 
  
<div style="margin-top: 10px;">
  <span style="display: inline-block;">
    <h3 style="display: inline;">{{request.session.active_article_count}}</h3>
    <span style="display: inline;">/</span>
    <h5 style="display: inline;opacity:0.3;">{{request.session.completed_article}}</h5>
    <span style="display: inline;">/</span>
    <h5 style="display: inline;opacity:0.3;">{{request.session.total_article_count}}</h5>
  </span>
</div>

<!-- <h3><span>{{request.session.active_article_count}}/{{request.session.total_article_count}}</span> </h3> -->
</div>
{% comment %} <a href="#" class="notification_btn">Today</a> {% endcomment %}
<div id="bar1" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{request.session.article_percent}}"></span>
</div>
</div>
</a>

<a href="{% url 'bundle_details' %}" class="bundle-link-disabled"><div class="single_quick_activity" >
<div class="count_content">
  <div>
    <span class="hover-element">
      <p style="display: inline;font-size: 1rem;">Bundle</p>
      <p style="display: inline;font-size: 0.5rem;">Month</p>
      <img style="display: inline;opacity:0.3;height: 15px;width: 15px;float: right;vertical-align: middle;" src="/static/img/interrogation.png" alt="Logo">
    </span>
  </div>

  <div style="margin-top: 10px;">
    <span style="display: inline-block;">
      <h3 style="display: inline;">{{request.session.progress_bundle}}</h3>
      <span style="display: inline;">/</span>
      <h5 style="display: inline;opacity:0.3;">{{request.session.complete_bundle}}</h5>
      <span style="display: inline;">/</span>
    <h5 style="display: inline;opacity:0.3;">{{request.session.totalBundle}}</h5>
    </span>
  </div>

<!-- <h3><span>{{request.session.active_bundle_count}}/{{request.session.total_bundle_count}}</span> </h3> -->
<!-- <h3><span>{{request.session.bundlesInfo}}</span> </h3> -->
</div>
{% comment %} <a href="#" class="notification_btn yellow_btn">This Week</a> {% endcomment %}
<div id="bar2" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{request.session.bundle_percent}}"></span>
</div>
</div></a>

<a href="{% url 'operator_details' %}" class="bundle-link-disabled"><div class="single_quick_activity">
<div class="count_content">
  <div>
    <span class="operator-hover-element">
      <p style="display: inline;font-size: 1rem;">Operator</p>
      <p style="display: inline;font-size: 0.5rem;">Today</p>
      <img style="display: inline;opacity:0.3;height: 15px;width: 15px;float: right;vertical-align: middle;" src="/static/img/interrogation.png" alt="Logo">
    </span>
  </div>
  <div style="margin-top: 10px;">
    <span style="display: inline-block;">
      <h3 style="display: inline;">{{request.session.active_operators_count}}</h3>
      <span style="display: inline;">/</span>
      <h5 style="display: inline;opacity:0.3;">{{request.session.total_operators_count}}</h5>
    </span>
  </div>

<!-- <h3><span>{{request.session.active_operators_count}}/{{request.session.total_operators_count}}</span> </h3> -->
<!-- <h3><span>{{request.session.operators_info}}</span> </h3> -->
</div>
{% comment %} <a href="#" class="notification_btn green_btn">This Month</a> {% endcomment %}
<div id="bar3" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{request.session.operator_percent}}"></span>
</div>
</div>
</a>

<a href="{% url 'machine_details' %}" class="bundle-link-disabled"><div class="single_quick_activity">
<div class="count_content">
  <div>
    <span class="operator-hover-element">
      <p style="display: inline;font-size: 1rem;">Machine</p>
      <p style="display: inline;font-size: 0.5rem;">Today</p>
      <img style="display: inline;opacity:0.3;height: 15px;width: 15px;float: right;vertical-align: middle;" src="/static/img/interrogation.png" alt="Logo">
    </span>
  </div>
<div style="margin-top: 10px;">
  <span style="display: inline-block;">
    <h3 style="display: inline;">{{request.session.active_machine_count}}</h3>
    <span style="display: inline;">/</span>
    <h5 style="display: inline;opacity:0.3;">{{request.session.total_machine_count}}</h5>
  </span>
</div>

<!-- <h3><span >{{request.session.machinesInfo}}</span></h3> -->
</div>
{% comment %} <a href="#" class="notification_btn violate_btn">Anual</a> {% endcomment %}
<div id="bar4" class="barfiller">
<div class="tipWrap">
<span class="tip"></span>
</div>
<span class="fill" data-percentage="{{request.session.machine_percent}}"></span>
</div>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>

<div class="col-lg-6">

  <div class="white_card card_height_100 mb_30">
    <div class="white_card_header">
    <div class="box_header m-0">
    <div class="main-title">
    <h5 class="m-0">Articles in month</h5>
    </div>
    <!-- <div class="header_more_tool">
    <div class="dropdown">
    <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
    <i class="ti-more-alt"></i>
    </span>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
    <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
    <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
    <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
    <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
    </div>
    </div>
    </div> -->
    </div>
    </div>
    <!-- <div class="d-flex align-items-center justify-content-center">
      <h4>Month Article</h4>
    </div> -->
    <div class="white_card_body pb-0">
    <canvas id="bundlebarChart" style="height:307px;"></canvas>
    </div>
    </div>
<!-- <div class="white_card card_height_100 mb_30">
<div class="white_card_header">
<div class="box_header m-0">
<div class="main-title">
<h3 class="m-0"></h3>
</div>
<div class="header_more_tool">
<div class="dropdown">
<span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
<i class="ti-more-alt"></i>
</span>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
<a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
<a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
<a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
<a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
</div>
</div>
</div>
</div>
</div>
<div class="white_card_body pb-0">
<div id="line-chart"> </div>
</div>
</div> -->
</div>
<div class="col-lg-6">

  <div class="white_card card_height_100 mb_30">
    <div class="white_card_header">
    <div class="box_header m-0">
    <div class="main-title">
    <h5 class="m-0">Active operators in month</h5>
    </div>
    <!-- <div class="header_more_tool">
    <div class="dropdown">
    <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
    <i class="ti-more-alt"></i>
    </span>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
    <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
    <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
    <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
    <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
    </div>
    </div>
    </div> -->
    </div>
    </div>
    <!-- <div class="d-flex align-items-center justify-content-center">
      <h4>Todays Active Operators</h4>
    </div> -->
    
    <div class="white_card_body pb-0">
    
    <canvas id="OperatorsLineChart" style="height:307px;"></canvas>
    </div>
    </div>
<!-- <div class="white_card card_height_100 mb_30">
<div class="white_card_header">
<div class="box_header m-0">
<div class="main-title">
<h3 class="m-0"></h3>
</div>
<div class="header_more_tool">
<div class="dropdown">
<span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
<i class="ti-more-alt"></i>
</span>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
<a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
<a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
<a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
<a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
</div>
</div>
</div>
</div>
</div>
<div class="white_card_body pb-0">
<div id="line-chart"> </div>
</div>
</div> -->
</div>

<div class="col-lg-12">

  <div class="white_card card_height_100 mb_30">
    <div class="white_card_header">
    <div class="box_header m-0">
    <div class="main-title">
    <h5 class="m-0">Completed bundles in last 30 days</h5>
    </div>
    <!-- <div class="header_more_tool">
    <div class="dropdown">
    <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
    <i class="ti-more-alt"></i>
    </span>
    <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
    <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
    <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
    <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
    <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
    <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
    </div>
    </div>
    </div> -->
    </div>
    </div>
    <!-- <div class="d-flex align-items-center justify-content-center">
      <h4>Todays Active Operators</h4>
    </div> -->
    
    <div class="white_card_body pb-0">
    
    <canvas id="bundlesLineChart" style="height:307px;"></canvas>
    </div>
    </div>
<!-- <div class="white_card card_height_100 mb_30">
<div class="white_card_header">
<div class="box_header m-0">
<div class="main-title">
<h3 class="m-0"></h3>
</div>
<div class="header_more_tool">
<div class="dropdown">
<span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
<i class="ti-more-alt"></i>
</span>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
<a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
<a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
<a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
<a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
</div>
</div>
</div>
</div>
</div>
<div class="white_card_body pb-0">
<div id="line-chart"> </div>
</div>
</div> -->
</div>

<!-- <div class="col-lg-6">
<div class="white_card card_height_100 mb_30">
<div class="white_card_header">
<div class="box_header m-0">
<div class="main-title">
<h3 class="m-0"></h3>
</div>
<div class="header_more_tool">
<div class="dropdown">
<span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
<i class="ti-more-alt"></i>
</span>
<div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
<a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
<a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
<a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
<a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
<a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
</div>
</div>
</div>
</div>
</div>
<div class="white_card_body pb-0">
<canvas id="barChart" style="height:307px;"></canvas>
</div>
</div>
</div> -->


<!-- <div class="col-lg-12">
  <div class="white_card card_height_100 mb_30">
  <div class="white_card_header">
  <div class="box_header m-0">
  <div class="main-title">
  <h3 class="m-0"></h3>
  </div>
  <div class="header_more_tool">
  <div class="dropdown">
  <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
  <i class="ti-more-alt"></i>
  </span>
  <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
  <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
  <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
  <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
  <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
  </div>
  </div>
  </div>
  </div>
  </div>
  <div class="white_card_body pb-0">
  <canvas id="bundlebarChart" style="height:307px;"></canvas>
  </div>
  </div>
  </div> -->

<!-- <div class="col-lg-6">
  <div class="white_card card_height_100 mb_30">
  <div class="white_card_header">
  <div class="box_header m-0">
  <div class="main-title">
  <h3 class="m-0"></h3>
  </div>
  <div class="header_more_tool">
  <div class="dropdown">
  <span class="dropdown-toggle" id="dropdownMenuButton" data-bs-toggle="dropdown">
  <i class="ti-more-alt"></i>
  </span>
  <div class="dropdown-menu dropdown-menu-right" aria-labelledby="dropdownMenuButton">
  <a class="dropdown-item" href="#"> <i class="ti-eye"></i> Action</a>
  <a class="dropdown-item" href="#"> <i class="ti-trash"></i> Delete</a>
  <a class="dropdown-item" href="#"> <i class="fas fa-edit"></i> Edit</a>
  <a class="dropdown-item" href="#"> <i class="ti-printer"></i> Print</a>
  <a class="dropdown-item" href="#"> <i class="fa fa-download"></i> Download</a>
  </div>
  </div>
  </div>
  </div>
  </div>
  <div class="white_card_body pb-0">
    <input type="date" id="Test_DatetimeLocal">
    <div class="QA_table">


      <table class="table pt-0 lms_table_active">
      <thead>
      <tr>
      
      <th scope="col">ID</th>
      <th scope="col">Name</th>
      <th scope="col">Count</th>
      </tr>
      </thead>
      <tbody>
      
      
      </tbody>
      </table>
      </div>
  </div>
  </div>
  </div> -->

</div>
</div>
</div>




<div class="footer_part default_footer">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12">
<div class="footer_iner text-center">
{% comment %} <p>2020 © Influence - Designed by <a href="#"> <i class="ti-heart"></i> </a><a href="#"> Dashboard</a></p> {% endcomment %}
</div>
</div>
</div>
</div>
</div>
</section>




<div id="back-top" style="display: none;">
<a title="Go to Top" href="#">
<i class="ti-angle-up"></i>
</a>
</div>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
  // Your Chart.js code here
  var name = [];
var hours = [];
var inActivehr = [];
var employeeStaus =[];
var total = [];
var myData = "{{ request.session.bundleGraphData }}";

// Now you can use myData in your JavaScript code


// Function to decode HTML entities
function decodeHTMLEntities(text) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    }

    // Decode the HTML-encoded data
    var decodedData = decodeHTMLEntities(myData);
    // Replace single quotes with double quotes for keys
    
    decodedData = decodedData.replace(/'([^']+)'/g, '"$1"')

    var jsondata = JSON.parse(decodedData)
    demoData(jsondata)
// Get the canvas element
var ctx = document.getElementById('bundlebarChart').getContext('2d');

// Access the data from request.session and assign it to a JavaScript variable


    // Parse the decoded data as JSON
    // var dataArray = JSON.parse(jsa);

    // // Now you can work with the dataArray as a JavaScript array of objects
    // console.log(dataArray);


// Define the chart data
var data = {
  labels: name,
  datasets: [{
    label: 'Completed',
    data: inActivehr,
    backgroundColor: "rgba(30,184,204,255)",
    borderColor: "rgba(30,184,204,255)",
    borderWidth: 0.5,
    stack: 'Stack 0',
  },
  {
    label: 'In Progress',
    data: hours,
    backgroundColor: "rgba(142,142,142,255)",
    borderColor: "rgba(142,142,142,255)",
    borderWidth: 0.5,
    stack: 'Stack 0',
  },
]
};

// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  interaction: {
      intersect: false,
      mode: 'index',
    },
    // tooltips: {
    //         enabled: true,
    //         mode: 'index',
    //         intersect: false,
    //         callbacks: {
    //             title: function(tooltipItems, data) {
    //                 // You can customize the title here
    //                 return 'Custom Title';
    //             },
    //             label: function(tooltipItem, data) {
    //                 // You can customize the label here
    //                 return 'Custom Label: ' + tooltipItem.yLabel;
    //             },
    //         }
    //     },
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: "In Progress", // Change the y-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
        beginAtZero: true,
          callback: function(value) {if (value % 1 === 0) {return value;}}
      }
    }],
    xAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Articles", // Change the x-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    y: {
      beginAtZero: true,
      stacked: true,
    },
    x: {
      beginAtZero: true,
      stacked: true
    }
  }
};



// Create the chart
var myChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});

function returnColor(params) {
  console.log(params);
  if (params === "Active") {
    return 'rgba(106, 177, 90, 0.5)';
  }
  else{
    return 'rgba(0, 123, 255, 1)';
  }
}

function demoData(data) {

  console.log("dd",data);



for (let i = 0; i < data.length; i++) {
  
  name.push(data[i].article_name)
  hours.push(parseInt(data[i].completed_bundles));
  inActivehr.push(parseInt(data[i].incompleted_bundles))
  total.push(parseInt(data[i].total_bundles))
  // employeeStaus.push(listData[i].status)
}

// console.log(name);
// console.log(hours);
}

});

</script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded', function () {
  // Your Chart.js code here
  var name = [];
var hours = [];
var inActivehr = [];
var employeeStaus =[];
var myData = "{{ request.session.operatorActiveInactiveTime }}";

// Now you can use myData in your JavaScript code
console.log(myData);

// Function to decode HTML entities
function decodeHTMLEntities(text) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    }

    // Decode the HTML-encoded data
    var decodedData = decodeHTMLEntities(myData);
    // Replace single quotes with double quotes for keys
    
    decodedData = decodedData.replace(/'([^']+)'/g, '"$1"')

    var jsondata = JSON.parse(decodedData)
demoData(jsondata)
// Get the canvas element
var ctx = document.getElementById('barChart').getContext('2d');

// Access the data from request.session and assign it to a JavaScript variable


    // Parse the decoded data as JSON
    // var dataArray = JSON.parse(jsa);

    // // Now you can work with the dataArray as a JavaScript array of objects
    // console.log(dataArray);


// Define the chart data
var data = {
  labels: name,
  datasets: [{
    label: 'hours',
    data: hours,
    backgroundColor: "rgba(30,184,204,255)",
    borderColor: "rgba(30,184,204,255)",
    borderWidth: 1,
    stack: 'Stack 0',
  },
  {
    label: 'In active hours',
    data: inActivehr,
    backgroundColor: "rgba(142,142,142,255)",
    borderColor: "rgba(142,142,142,255)",
    borderWidth: 1,
    stack: 'Stack 0',
  }
]
};

// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Active / In active", // Change the y-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    xAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Operators", // Change the x-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    y: {
      beginAtZero: true,
      stacked: true,
    },
    x: {
      beginAtZero: true,
      stacked: true
    }
  },
  tooltips: {
        callbacks: {
            label: function(tooltipItem) {
              // const dataset = context.chart.data.datasets[context.datasetIndex];
            const customData =  tooltipItem.yLabel;
            
            // Convert custom data to hours, minutes, and seconds
            const hours = Math.floor(customData);
            const minutes = Math.floor((customData - hours) * 60);
            const seconds = Math.floor((customData - hours - minutes / 60) * 3600);
            
            return `Duration: ${hours} hr ${minutes} min ${seconds} sec`;
                // return "$" + tooltipItem.yLabel + " and so worth it !";
            }
        }
    }
};

// Create the chart
var myChart = new Chart(ctx, {
  type: 'bar',
  data: data,
  options: options
});

function returnColor(params) {
  console.log(params);
  if (params === "Active") {
    return 'rgba(106, 177, 90, 0.5)';
  }
  else{
    return 'rgba(0, 123, 255, 1)';
  }
}

function demoData(data) {
  var listData=[{
    'id':0,
    'name':'',
    "status":"rgba(30,184,204,255)",
    "hours":0
  },
  {
    'id':1,
    'name':'Abdul',
    "status":"rgba(30,184,204,255)",
    "hours":13
  },
  {
    'id':2,
    'name':'Hamza',
    "status":"rgba(30,184,204,255)",
    "hours":6
  },
  {
    'id':3,
    'name':'Ibrahim',
    "status":"rgba(106, 177, 90, 0.5)",
    "hours":7
  },
  {
    'id':4,
    'name':'Adil',
    "status":"rgba(106, 177, 90, 0.5)",
    "hours":9
  },
  {
    'id':5,
    'name':'Javaid',
    "status":"rgba(157, 10, 14, 0.5)",
    "hours":9
  },
  {
    'id':3,
    'name':'Ali',
    "status":"rgba(106, 177, 90, 0.5)",
    "hours":7
  },
  {
    'id':3,
    'name':'Usman',
    "status":"rgba(157, 10, 14, 0.5)",
    "hours":7
  },
]



for (let i = 0; i < data.length; i++) {
  
  name.push(data[i].name)
  console.log('qq' , convertTimeToHours(data[i].InActiveDuration));
  hours.push(convertTimeToHours(data[i].activeDuration));
  inActivehr.push(convertTimeToHours(data[i].InActiveDuration))
  // employeeStaus.push(listData[i].status)
}
// Convert time duration string to hours
function convertTimeToHours(timeString) {
  const [hours, minutes, seconds] = timeString.split(":").map(Number);
  const totalHours = hours + minutes / 60 + seconds / 3600;
  return totalHours;
}
console.log(name);
console.log(hours);
}

});

</script>

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded',function () {
    var ctx = document.getElementById('OperatorsLineChart').getContext('2d');
    var myData = "{{ request.session.activeOperatorsCountMonthly }}";

    console.log(myData);

    function decodeHTMLEntities(text) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    }

    // Decode the HTML-encoded data
    var decodedData = decodeHTMLEntities(myData);
    // Replace single quotes with double quotes for keys
    
    decodedData = decodedData.replace(/'([^']+)'/g, '"$1"')

    var jsondata = JSON.parse(decodedData)

    console.log(jsondata);
    var dates = []
    var values =[]

    for (const date in jsondata) {
    const value = jsondata[date];
    dates.push(date)
    values.push(parseInt(value))
    console.log(`Date: ${date}, Value: ${value}`);
}
// Access the data from request.session and assign it to a JavaScript variable


    // Parse the decoded data as JSON
    // var dataArray = JSON.parse(jsa);

    // // Now you can work with the dataArray as a JavaScript array of objects
    // console.log(dataArray);


// Define the chart data
var data = {
  labels: dates,
  datasets: [{
    label: 'Counts',
    data: values,
    backgroundColor: "rgba(30,184,204,255)",
    borderColor: "rgba(30,184,204,255)",
    // borderWidth: 1,
    // stack: 'Stack 0',
  },
  // {
  //   label: 'In active hours',
  //   data: inActivehr,
  //   backgroundColor: "rgba(142,142,142,255)",
  //   borderColor: "rgba(142,142,142,255)",
  //   // borderWidth: 1,
  //   // stack: 'Stack 0',
  // }
]
};

// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Active operator", // Change the y-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        beginAtZero:true,
        fontFamily:'comfortaa, cursive',
        callback: function(value) {if (value % 1 === 0) {return value;}}
      }
    }],
    xAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Dates", // Change the x-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    y: {
      beginAtZero: true,
      min:0
    },
    x: {
      beginAtZero: true,
      stacked: false
    }
  },
};

// Create the chart
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: options
});
  })
</script>


<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script>
  document.addEventListener('DOMContentLoaded',function () {
    var ctx = document.getElementById('bundlesLineChart').getContext('2d');
    var bundleData = "{{ request.session.completedBundlesWRTarticles }}";
    console.log(bundleData);

    function decodeHTMLEntities(text) {
        var textarea = document.createElement('textarea');
        textarea.innerHTML = text;
        return textarea.value;
    }

    // Decode the HTML-encoded data
    var decodedData = decodeHTMLEntities(bundleData);
    // Replace single quotes with double quotes for keys
    
    decodedData = decodedData.replace(/'([^']+)'/g, '"$1"')

    var jsondata = JSON.parse(decodedData)

    console.log(jsondata);
    var dates = []
    var values =[]
    var datasets =[]

    var resulter = []

    for (const bundle in jsondata) {
    const value = jsondata[bundle];
    // dates.push(date)
    // values.push(parseInt(value))
    console.log(bundle);
    for (resultCount in value){
      const resultData = value[resultCount]
      datasets.push({"label":bundle,"data":resultData,"date":resultCount,"borderColor":Math.floor(Math.random()*16777215).toString(16)})
      // console.log("resultData1",resultData);
    }

    console.log(datasets);

    const output = {};

    datasets.forEach(item => {
    const label = item.label;
    const data = item.data;
    const date = item.date;
    const borderColor = item.borderColor

    if (!output[label]) {
        output[label] = {
            label: label,
            data: [],
            date: [],
            borderColor:'#'+borderColor,
            fill: false,
        };
    }

    output[label].data.push(data);
    output[label].date.push(date);
});

// Convert to an array of objects
resulter = Object.values(output);

console.log(resulter);
}
// Access the data from request.session and assign it to a JavaScript variable


    // Parse the decoded data as JSON
    // var dataArray = JSON.parse(jsa);

    // // Now you can work with the dataArray as a JavaScript array of objects
    // console.log(dataArray);


// Define the chart data
var data = {
  labels: resulter[0].date,
  datasets:resulter
};

console.log("data",data);

// Configure the chart options
var options = {
  responsive: true,
  maintainAspectRatio: false,
  responsive: true,
    interaction: {
      mode: 'index',
      intersect: false,
    },
    stacked: false,
  scales: {
    yAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Bundle counts", // Change the y-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
        callback: function(value) {if (value % 1 === 0) {return value;}}
      }
    }],
    xAxes: [{
      scaleLabel: {
        display: true,
        labelString: "Dates", // Change the x-axis label here
        fontStyle: 'bold',
        fontSize:16,
        fontFamily:'comfortaa, cursive',
        fontColor:'#000000'
      },
      ticks: {
        fontColor: '#000000', 
        fontFamily:'comfortaa, cursive',
      }
    }],
    y: {
      beginAtZero: false,
      stacked: false,
    },
    x: {
      beginAtZero: true,
      stacked: false
    }
  },
};

// Create the chart
var myChart = new Chart(ctx, {
  type: 'line',
  data: data,
  options: options
});
  })
</script>



<script>
  // Wait for the page to load completely
  window.onload = function () {
    // Enable the link(s) once the page has loaded
    var bundleLinks = document.querySelectorAll('.bundle-link-disabled');
    bundleLinks.forEach(function (link) {
      link.classList.remove('bundle-link-disabled');

      // Optionally, you can restore the original cursor and opacity values if needed
       link.style.cursor = 'pointer';
      link.style.opacity = '1';
    });

    // Add any additional actions you want to perform after the page has loaded
    // ...
  };
</script>


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"></script>

<script>
  const apiDropdown = document.getElementById('apiDropdown');
  apiDropdown.addEventListener('change', function () {
            // Get the default value of the dropdown
            // const defaultDropdownValue = document.querySelector('#apiDropdown option[selected]').value;
            const selectedValue = this.value;
            getMachine(selectedValue);
            // Display the default value in the console
            console.log('Default Dropdown Value:',selectedValue );
        });

getMachine('WEEK');
getOperator('');

var dateInput = document.getElementById("Test_DatetimeLocal");
dateInput.addEventListener("input", function() {
  var selectedDate = dateInput.value;
  console.log(selectedDate);
  getOperator(selectedDate);
});
  function getMachine(params) {
    console.log('starting');
  var data = {
        'date': params
    };
    //console.log(data);
    // Serialize the data object
    var serializedData = JSON.stringify(data);
    console.log(serializedData);
    
    // Get the CSRF token value from the cookie
    var csrftoken = Cookies.get('csrftoken');
  $.ajax({
      url: '{% url "getmachineReporting" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        // console.log('Received the ID on the server');
        console.log('response',response.bundle_data.total_pieces);
        var stringd = "There are total "+response.bundle_data.total_pieces+" in a "+ params;
        var targetParagraph = document.getElementById("target-paragraph");
        targetParagraph.textContent = stringd
        //  Totalbundle_data = response.bundle_data; // Assuming the server returns the 'data_steps' in the response

        //  updateBundleOnPage(Totalbundle_data);
        
  
        // Handle the response from the server if needed
      },
      error: function(error) {
        // Handle the error response, e.g., show an error message
        alert('Error submitting the review. Please try again.');
      }
    });
  }
  function getOperator(params) {
    console.log('starting');
  var data = {
        'date': params
    };
    //console.log(data);
    // Serialize the data object
    var serializedData = JSON.stringify(data);
    console.log(serializedData);
    
    // Get the CSRF token value from the cookie
    var csrftoken = Cookies.get('csrftoken');
  $.ajax({
      url: '{% url "getoperatorReporting" %}',
      method: 'POST',
      data: serializedData,
      contentType: 'application/json',
      beforeSend: function(xhr, settings) {
        xhr.setRequestHeader('X-CSRFToken', csrftoken);
      },
      success: function(response) {
        // console.log('Received the ID on the server');
        console.log('response',response);
        var table = $('.lms_table_active').DataTable();
        table.clear().draw(); // Clear existing rows in the table
        if ( response.dataBundle == 'No data found'){
             table.clear().draw(); // Clear any existing rows (if any)
             //table.rows.add(['No data found']).draw();
          }
        else {
        // Iterate over the response and add new rows to the DataTable instance
        for (var i = 0; i < response.response.length; i++) {
          var orderNo = i + 1;
          var row = response.response[i];
          var newRow = [
            row.operator_ID,
            row.operator_name,
            row.bundle_count,
          ];

          table.row.add(newRow);
        }

        // Draw the table with the new data
        table.draw();
      }
        // var stringd = "There are total "+response.bundle_data.total_pieces+" in a "+ params;
        // var targetParagraph = document.getElementById("target-paragraph");
        // targetParagraph.textContent = stringd
        //  Totalbundle_data = response.bundle_data; // Assuming the server returns the 'data_steps' in the response

        //  updateBundleOnPage(Totalbundle_data);
        
  
        // Handle the response from the server if needed
      },
      error: function(error) {
        // Handle the error response, e.g., show an error message
        alert('Error submitting the review. Please try again.');
      }
    });
  }
  
</script>





{% endblock %}

