const express = require('express');

const enrollmentApp = 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`);

let rqf = new ReqQueryFields();

// Complete range of the enrollments dataset.
// Returns a tuple of start and ending years of the complete enrollments dataset.
enrollmentApp.get('/year_range', (req, res, next) => {
    req.sql.from('matricula')
    .field('MIN(matricula.ano_censo)', 'start_year')
    .field('MAX(matricula.ano_censo)', 'end_year');
    next();
}, query, response('range'));

enrollmentApp.get('/location', (req, res, next) => {
    req.sql = squel.select()
        .field('id')
        .field('descricao', 'name')
        .from('localizacao');
    next();
}, query, response('location'));

// Returns all educational levels avaible
enrollmentApp.get('/education_level', (req, res, next) => {
    req.sql.from('serie_ano')
    .field('id')
    .field('nome', 'name');
    next();
}, query, response('education_level'));

// Returns all adm dependencies
enrollmentApp.get('/adm_dependency', (req, res, next) => {
    req.sql.from('dependencia_adm')
    .field('id', 'id')
    .field('nome', 'name');
    next();
}, query, response('adm_dependency'));

// Return genders
enrollmentApp.get('/gender', (req, res, next) => {
    req.result = [
        {id: 1, name: 'Masculino'},
        {id: 2, name: 'Feminino'}
    ];
    next();
}, response('gender'));

// Return ethnic group
enrollmentApp.get('/ethnic_group', (req, res, next) => {
    req.result = [
        {id: 0, name: 'Não declarada'},
        {id: 1, name: 'Branca'},
        {id: 2, name: 'Preta'},
        {id: 3, name: 'Parda'},
        {id: 4, name: 'Amarela'},
        {id: 5, name: 'Indígena'}
    ];
    next();
}, response('ethnic_group'));

rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'adm_dependency',
    table: 'dependencia_adm',
    tableField: 'nome',
    resultField: 'adm_dependency_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'dependencia_adm_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'education_level',
    table: 'serie_ano',
    tableField: 'nome',
    resultField: 'education_level_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'serie_ano_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'region',
    table: 'regiao',
    tableField: 'nome',
    resultField: 'region_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'regiao_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'state',
    table: 'estado',
    tableField: 'nome',
    resultField: 'state_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'escola_estado_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'city',
    table: 'municipio',
    tableField: 'nome',
    resultField: 'city_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'escola_municipio_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'school',
    table: 'escola',
    tableField: 'nome_escola',
    resultField: 'school_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'escola_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'location',
    table: 'localizacao',
    tableField: 'descricao',
    resultField: 'location_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'localizacao_id',
        foreignTable: 'matricula'
    }
}).addValue({
    name: 'min_year',
    table: 'matricula',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: 'matricula',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'gender',
    table: 'matricula',
    tableField: 'sexo',
    resultField: 'gender_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'sexo'
    }
}).addValue({
    name: 'ethnic_group',
    table: 'matricula',
    tableField: 'cor_raca',
    resultField: 'ethnic_group_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'ethnic_group_id'
    }
});

enrollmentApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {
    log.debug(req.sql.toParam());
    req.sql.field('COALESCE(COUNT(matricula.id), 0)', 'total')
    .field("'Brasil'", 'name')
    .field('matricula.ano_censo', 'year')
    .from('matricula')
    .group('matricula.ano_censo')
    .order('matricula.ano_censo')
    .where('matricula.tipo=0 OR matricula.tipo=1 OR matricula.tipo=2 OR matricula.tipo=3');
    next();
}, query, response('enrollment'));

module.exports = enrollmentApp;