/*
Copyright (C) 2024 Centro de Computacao Cientifica e Software Livre
Departamento de Informatica - Universidade Federal do Parana - C3SL/UFPR

This file is part of simcaq-node.

simcaq-node is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

simcaq-node is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with simcaq-node.  If not, see <https://www.gnu.org/licenses/>.
*/

const express = require('express');

const studentCostApp = express.Router();

const libs = `${process.cwd()}/libs`;

const squel = require('squel');

const query = require(`${libs}/middlewares/query`).query;

const response = require(`${libs}/middlewares/response`);

const ReqQueryFields = require(`${libs}/middlewares/reqQueryFields`);

const aggregateData = require(`${libs}/middlewares/aggregateData`);

const id2str = require(`${libs}/middlewares/id2str`);

const config = require(`${libs}/config`); 

const cache = require('apicache').options({ debug: config.debug, statusCodes: {include: [200]} }).middleware;

let rqf = new ReqQueryFields();

studentCostApp.use(cache('15 day'));

studentCostApp.get('/years', (req, res, next) => {
    req.sql.from('despesas')
    .field('DISTINCT despesas.ano_censo', 'year')
    .where('despesas.ano_censo is not null')
    next();
}, query, response('years'));

studentCostApp.get('/type', (req, res, next) => {
    req.result = []

    req.result.push({ id: 1, name: "Rede Estadual" });
    req.result.push({ id: 2, name: "Rede Municipal" });
    next();
}, response('type'));

rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'min_year',
    table: 'despesas',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: 'despesas',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'region',
    table: 'estado',
    tableField: ['nome_ente', 'cod_ibge', 'id', 'regiao_id'],
    resultField: ['state_name', 'state_cod_ibge', 'state_id', 'region_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'regiao_id',
    },
    join: {
        primary: 'id',
        foreign: 'cod_ibge',
        foreignTable: 'despesas'
    }
})

studentCostApp.get('/', rqf.parse(), rqf.build(),  (req, res, next) => {
    if (req.query.dims && req.query.dims.includes('despesas')) {
        let obj = {};
        let whereCondition = req.query.filter.includes("region") ? "" : "despesas.cod_ibge = 0";
        let filterId;
        let typeFilter = false;
        const filters = req.query.filter.split(",");
        filters.forEach((filter) => {
            if (filter.includes("state") || filter.includes("city")) {
                filterId = Number(filter.split(":")[1].replace(/"/g, ""));
                whereCondition = `despesas.cod_ibge = ${filterId}`
            }
        })

        if (req.query.filter) {
            const jsonString = `{${req.query.filter.replace(/(\w+):/g, '"$1":')}}`;
            obj = JSON.parse(jsonString);
            if (obj.type) {
                if (obj.type.includes("1") && !obj.type.includes("2"))
                    whereCondition = "despesas.cod_ibge >= 11 and despesas.cod_ibge <= 53"
                else if (obj.type.includes("2") && !obj.type.includes("1"))
                    whereCondition = "despesas.cod_ibge > 53"

                typeFilter = true;
            }
        }

        if (!typeFilter || (typeFilter && (!obj.state && !obj.city && !obj.region))) {
            req.sql.from('despesas')
                .field('despesas.ano_censo', 'year')
                .field(`SUM(despesas) / SUM(matriculas_publica)`, '(total_gasto_aluno_ano_publica)')
                .field(`SUM(despesas) / SUM(matriculas_publica) / 12`, 'total_gasto_aluno_mes_publica')
                .field(`SUM(despesas) / SUM(matriculas_publicas_mais_conveniada)`, 'total_gasto_aluno_ano_publica_mais_conveniada')
                .field(`SUM(despesas) / SUM(matriculas_publicas_mais_conveniada) / 12`, 'total_gasto_aluno_mes_publica_mais_conveniada')
                .where(`${whereCondition}`)
                .group('despesas.ano_censo')
                .order('despesas.ano_censo')
        }
    }

    next();
}, query, aggregateData, response('student_cost'));

module.exports = studentCostApp;