const fs = require('fs');
const path = require('path');
const moment = require('moment');
const _ = require('lodash'); // TODO
const log = require('loglevel');
const formData = require('form-data');

const constants = require('../models/constants');
const constantsXml = require('../models/constants-xml');
const enums = require('../models/enums');
const enumsXml = require('../models/enums-xml');

const InvoiceServ = require('../services/invoice');

class InvoiceCtrl {
    constructor () {
        this.service = new InvoiceServ();

    }

    invoiceUpload = async (req, res) => {
        try {
            const invoice = req.body;

            let fileData = invoice.file.split(',')[1];
            let fileType = invoice.file.split(';')[0].split('/')[1];
            let formContent = new formData();
            formContent.append('file', Buffer.from(fileData, 'base64'));
            formContent.append('name', 'invoice'+invoice.fareItemIssuedNumber+'.'+fileType);

            const invoiceData = {
                file: formContent,
                invoiceInfo: {
                    fareItemIssuedNumber: invoice.fareItemIssuedNumber
                }
            };

            const invoiceUpload = await this.service.invoiceUpload(invoiceData);

            res.status(200).json(invoiceUpload);
        } catch (err) {
            log.error(err);
            res.status(400).json({ error: err.message });
        }
    }

    invoiceDownload = async (req, res) => {
        try {
            const invoice = req.body;

            const invoiceData = {
                fareItemIssuedNumber: invoice.fareItemIssuedNumber
            };

            const invoiceDownload = await this.service.invoiceDownload(invoiceData);

            res.status(200).json(invoiceDownload);
        } catch (err) {
            log.error(err);
            res.status(400).json({ error: err.message });
        }
    }

}

module.exports = InvoiceCtrl;
