var cashTransactionModel = require('../models/cashTransactionModel.js');

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

  list: async function (req, res) {
    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.find({ year, month }, { _id: 0, __v: 0, raw: 0 });
      } else {
        transactions = await cashTransactionModel.find({}, { _id: 0, __v: 0, raw: 0 });
      }

      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, res) {
    const rawString = req.body.messageBody;

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

    const transaction = new cashTransactionModel({
      raw: 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 transaction.save()
    if (trans) {
      return res.status(201).json(trans);
    }
    else {
      return res.status(400).json({ message: "something went wrong" });
    }
  },

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