import { type Request, type Response } from "express";

import cashTransactionModel from '../models/cashTransactionModel';

const types = ['ZAVRNITEV POS NAKUP', 'POS NAKUP', 'BA DVIG', 'priliv', 'SDD', 'SPLET/TEL NAKUP', 'PREDAVTORIZACIJE'];

// TODO hendel this PREDAVTORIZACIJA

export default {

  list: async function (req: Request, res: Response) {
    try {
      var transactions;
      const date = req.body.date;

      if (date) {
        const splitDate = date.split('-');
        var year = splitDate[0];
        var month = splitDate[1];
        year = parseInt(year);
        month = parseInt(month);
        transactions = await cashTransactionModel.findWithPar(year, month);
      } else {
        transactions = await cashTransactionModel.find();
      }

      const data = { transactions: transactions, types: types };

      return res.json(data);
    } catch (err) {
      return res.status(500).json({
        message: 'Error when getting transactions.',
        error: err
      });
    };
  },

  create: async function (req: Request, res: Response) {
    const rawString = req.body.messageBody;

    if (rawString == "") return res.status(400).json({ message: "empty string" });

    const transaction = {
      rawMessage: rawString,
      day: 0,
      month: 0,
      year: 0,
      amount: 0,
      type: -1,
      company: "",
    };

    const datePattern = /(0[1-9]|[12][0-9]|3[01])\.(0[1-9]|1[0-2])\.(19|20)\d{2}/;
    const amountPattern = /\d{1,3}(?:[.]\d{3})*(?:[.,]\d{2})(?=\sEUR)/;
    const companyPattern1 = /(?<=(UR,|\sod)\s).*?(?=\s(na\s|za\s|Inf))/;

    for (var i = 0; i < types.length; i++) {
      if (rawString.includes(types[i])) {
        transaction.type = i;
        break;
      }
    }

    if (transaction.type != -1) {
      const amountMatch = rawString.match(amountPattern);
      if (amountMatch) {
        const amount = amountMatch[0].replace('.', '').replace(',', '.');
        transaction.amount = parseFloat(amount);
      }

      const companyMatch1 = rawString.match(companyPattern1);
      if (companyMatch1) transaction.company = companyMatch1[0];

      const dateMatch = rawString.match(datePattern);
      if (dateMatch) {
        const date = dateMatch[0].split('.');
        transaction.day = date[0];
        transaction.month = date[1];
        transaction.year = date[2];
      }
    }
    const trans = await cashTransactionModel.save(transaction.rawMessage, transaction.day, transaction.month, transaction.year, transaction.amount, transaction.type, transaction.company);
    if (trans) {
      return res.status(201).json(trans);
    }
    else {
      return res.status(400).json({ message: "something went wrong" });
    }
  },

  delete: async function (req: Request, res: Response) {
    cashTransactionModel.findOneAndDelete(-1)
      .then(data => {
        res.status(201).json({ message: "OK" });
      });
  },
};