import Chart from 'chart.js/auto'
import * as elements from "../elementcreate";

interface Transaction {
  day: number;
  month: number;
  year: number;
  amount: number;
  type: number;
  company: string;
}

var types: Array<string> = [];

async function submitMedia(event: SubmitEvent) {
  event.preventDefault();
  const pass = document.getElementById("pass") as HTMLInputElement | null;
  const date = document.getElementById("date") as HTMLInputElement | null;
  if (!pass || !date) return;

  if (pass.value == "") return;

  try {
    const result = await fetch('/api/cash/list', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ pass: pass.value, date: date.value }),
    })

    const data: { types: string[]; transactions: Array<Transaction>; } = await result.json();
    types = data.types;

    renderData(data.transactions);
    renderChart(data.transactions);
  } catch (e) {
    console.log(e);
  }

  pass.value = "";
};

document.addEventListener('DOMContentLoaded', async () => {
  document.getElementById("myform")?.addEventListener("submit", submitMedia);
});

function renderChart(transactions: Array<Transaction>) {

  const cash = [];

  for (let index = 0; index < 7; index++) {
    cash.push(0);
  }

  for (let index = 0; index < transactions.length; index++) {
    const element = transactions[index];

    const type = element.type;
    const amount = element.amount;
    if (type == -1) continue;
    cash[type] += amount;
  }

  var data = {
    labels: types,
    datasets: [{
      label: '',
      data: cash
    }]
  };

  var ctx = document.getElementById('acquisitions') as HTMLCanvasElement | null;
  if (ctx == null) return;
  new Chart(
    ctx,
    {
      type: 'pie',
      data: data,
    }
  );
};

function getTypeName(type: number) {
  if (type == -1) return "UNKNOWN";
  return types[type];
}

function renderData(transactions: Array<Transaction>) {
  var tbody = document.getElementById("tbody");
  if (tbody == null) return;
  tbody.innerHTML = "";

  transactions
    .sort((a, b) => a.day - b.day)
    .sort((a, b) => a.month - b.month)
    .sort((a, b) => a.year - b.year);

  for (let index = 0; index < transactions.length; index++) {
    const element = transactions[index];

    var row =
      <tr>
        <th scope="row">{index}</th>
        <td>{element.day}</td>
        <td>{element.month}</td>
        <td>{element.year}</td>
        <td>{element.amount}</td>
        <td>{getTypeName(element.type)}</td>
        <td>{element.company}</td>
      </tr>

    tbody.appendChild(row);

  }
};