const resultsTable = document.querySelector('#results-table').getElementsByTagName('tbody')[0];;
const resultRowTemp = document.querySelector('#results-row-temp');
const contentContainer = document.querySelector('.content-container');
let search = null;
try {
    search = JSON.parse(localStorage.getItem('selected-search'));
}
catch {
    window.location = '../my-searches/my-searches.html';
}

drawGraph();
loadSearch();
async function loadSearch() {
    for(let result of search.results)
    {
        let createdDate = new Date(result.created);
        let dateStr = createdDate.toLocaleDateString();
        let timeStr = createdDate.toLocaleTimeString();
        let row = resultRowTemp.content.cloneNode(true).querySelector('tr');
        row.querySelector('.date').textContent = dateStr;
        row.querySelector('.time').textContent = timeStr;
        row.querySelector('.result-num').textContent = result.result_num;
        resultsTable.appendChild(row);
    }
}


function drawGraph() {
    const ctx = document.getElementById('myChart');
    let labels = [];
    let data = [];
    let dataByDate = {};
    for(let result of search.results)
    {
        let createdDate = new Date(result.created);
        let dateStr = createdDate.toLocaleDateString();
        // let timeStr = createdDate.toLocaleTimeString();
        // labels.push(dateStr);
        // data.push(result.result_num);
        dataByDate[dateStr] = result.result_num;
    }
    for(let date in dataByDate)
    {
        data.push(dataByDate[date]);
        labels.push(date);
    }
    new Chart(ctx, {
      type: 'line',
      data: {
        labels: labels,
        datasets: [{
          label: 'Anzahl der Inserate',
          data: data,
          borderWidth: 3
        }]
      },
      options: {
        scales: {
          y: {
            beginAtZero: true
          }
        }
      }
    });
}