const express = require('express');

const idhmApp = express.Router();

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

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

const squel = require('squel');

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

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

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

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();

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

idhmApp.get('/year_range', (req, res, next) => {
    req.sql.from('adh_idh')
    .field('MIN(adh_idh.ano_censo)', 'start_year')
    .field('MAX(adh_idh.ano_censo)', 'end_year')
    .where('adh_idh.ano_censo <> 2014 AND adh_idh.ano_censo <> 2013');
    next();
}, query, (req, res, next) => {
    req.sql.from('adh_idh_uf')
    .field('MIN(adh_idh_uf.ano_censo)', 'start_year')
    .field('MAX(adh_idh_uf.ano_censo)', 'end_year')
    .where('adh_idh_uf.ano_censo <> 2014 AND adh_idh_uf.ano_censo <> 2013');
    req.old_result = req.result;
    next();
}, query, (req, res, next) => {
    if (req.old_result[0].start_year < req.result[0].start_year) {
        req.result[0].start_year = req.old_result[0].start_year;
    }
    if (req.old_result[0].end_year > req.result[0].end_year) {
        req.result[0].end_year = req.old_result[0].old_result;
    }
    next();
}, query, response('range'));

idhmApp.get('/years', (req, res, next) => {
    req.sql.from('adh_idh')
    .field('DISTINCT adh_idh.ano_censo', 'year')
    .where('adh_idh.ano_censo <> 2014 AND adh_idh.ano_censo <> 2013');
    next();
}, query, (req, res, next) => {
    req.oldResult = req.result;

    req.sql = squel.select();

    req.sql.from('adh_idh_uf')
    .field('DISTINCT adh_idh_uf.ano_censo', 'year')
    .where('adh_idh_uf.ano_censo <> 2014 AND adh_idh_uf.ano_censo <> 2013');
    next();
}, query, (req, res, next) => {
    let result = Object.assign(req.oldResult, req.result);
    req.result = result;
    next();
}, response('years'));

idhmApp.get('/source', (req, res, next) => {
    req.sql.from('fonte')
    .field('fonte', 'source')
    .where('tabela = \'adh_idh\'');
    next();
}, query, response('source'));

idhmApp.get('/IDHM_level', (req, res, next) => {
    req.result = [
        {id: null, name: 'Não classificada'},
        {id: 1, name: 'Muito Baixa'},
        {id: 2, name: 'Baixo'},
        {id: 3, name: 'Médio'},
        {id: 4, name: 'Alto'},
        {id: 5, name: 'Muito Alto'}
    ];
    next();
}, response('IDHM_level'));

rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'city',
    table: 'municipio',
    tableField: 'nome',
    resultField: 'city_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'municipio_id',
        table: 'adh_idh'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'adh_idh'
    }
}).addValue({
    name: 'state',
    table: 'estado',
    tableField: 'nome',
    resultField: 'state_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'estado_id',
        table: '@'
    },
    join: {
        primary: 'id',
        foreign: 'estado_id',
        foreignTable: '@'
    }
}).addValue({
    name: 'min_year',
    table: '@',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        table: '@',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: '@',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        table: '@',
        field: 'ano_censo'
    }
}).addValue({
    name: 'idhm_level',
    table: '@',
    tableField: 'idhm_nivel',
    resultField: 'idhm_level_id',
    where: {
        relation: '=',
        type: 'integer',
        table: '@',
        field: 'idhm_nivel'
    }
});


idhmApp.get('/', rqf.parse(), (req, res, next) => {
  log.debug(req.sql.toParam());
      if (("city" in req.dims) || ("city" in req.filter)) {
          req.sql.from('adh_idh')
          .field('adh_idh.idhm', 'total')
          .field('adh_idh.ano_censo', 'year')
          .field('adh_idh.municipio_id', 'city_id')
          .field('adh_idh.estado_id', 'state_id')
          .group('adh_idh.idhm')
          .group('adh_idh.ano_censo')
          .group('adh_idh.municipio_id')
          .group('adh_idh.estado_id')
      } else if (("state" in req.filter) || ("state" in req.dims)) {
          req.sql.from('adh_idh_uf')
          .field('adh_idh_uf.idhm', 'total')
          .field('adh_idh_uf.ano_censo', 'year')
          .field('adh_idh_uf.estado_id', 'state_id')
          .group('adh_idh_uf.idhm')
          .group('adh_idh_uf.ano_censo')
          .group('adh_idh_uf.estado_id')
        } else {
            res.status(400);
            next({
                status: 400,
                message: 'Wrong/No filter specified'
            });
        }
        next();
}, rqf.build(), query, id2str.transform(), response('idhm'));

module.exports = idhmApp;