const express = require('express');

const schoolApp = express.Router();

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

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

const squel = require('squel');

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

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

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

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

const request = require(`request`);

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

const passport = require('passport');

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

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

let rqf = new ReqQueryFields();
let rqfCount = new ReqQueryFields();

// Return location
schoolApp.get('/year_range', cache('15 day'), (req, res, next) => {
    req.sql.from('escola')
    .field('MIN(escola.ano_censo)', 'start_year')
    .field('MAX(escola.ano_censo)', 'end_year');
    next();
}, query, response('range'));

schoolApp.get('/years', cache('15 day'), (req, res, next) => {
    req.sql.from('escola').
    field('DISTINCT escola.ano_censo', 'year');
    next();
}, query, response('years'));

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

schoolApp.get('/location', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: 1, name: 'Urbana'},
        {id: 2, name: 'Rural'}
    ];
    next();
}, response('location'));

schoolApp.get('/diff_location', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: 0, name: "A escola não está em localidade diferenciada"},
        {id: 1, name: "Área de assentamento"},
        {id: 2, name: "Terra indígena"},
        {id: 3, name: "Terra remanescente de quilombos"},
    ];
    next();
}, response('rural_location'));

schoolApp.get('/adm_dependency', (req, res, next) => {
    req.result = [];
    for(let i = 1; i <= 4; ++i) {
        req.result.push({
            id: i,
            name: id2str.admDependency(i)
        });
    };
    next();
}, response('adm_dependency'));

schoolApp.get('/adm_dependency_detailed', cache('15 day'), (req, res, next) => {
    req.result = [];
    for(let i = 1; i <= 6; ++i) {
        req.result.push({
            id: i,
            name: id2str.admDependencyPriv(i)
        });
    };
    next();
}, response('adm_dependency_detailed'));

schoolApp.get('/government_agreement', cache('15 day'), (req, res, next) => {
    req.result = [];
    for(let i = 1; i <= 6; ++i) {
        req.result.push({
            id: i,
            name: id2str.govermentAgreement(i)
        });
    };
    next();
}, response('government_agreement'));

schoolApp.get('/agreement', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: 1, name: 'Municipal'},
        {id: 2, name: 'Estadual'},
        {id: 3, name: 'Estadual e Municipal'}
    ];
    next();
}, response('agreement'));

schoolApp.get('/education_day_care_child', (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_day_care_child'));

schoolApp.get('/education_preschool_child', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_preschool_child'));

schoolApp.get('/education_begin_elementary_school', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_begin_elementary_school'));

schoolApp.get('/education_end_elementary_school', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_end_elementary_school'));

schoolApp.get('/education_middle_school', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_middle_school'));

schoolApp.get('/education_professional', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_professional'));

schoolApp.get('/education_eja', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: null, name: 'Não Declarado'},
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'}
    ];
    next();
}, response('education_eja'));


schoolApp.get('/arrangement', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: 0, name: 'Creche'},
        {id: 1, name: 'Pré Escola'},
        {id: 2, name: 'Ensino Fundamental - AI'},
        {id: 3, name: 'Ensino Fundamental - AF'},
        {id: 4, name: 'Ed. Infantil Unificada/Multietapa/Multissérie/Correção fluxo'},
        {id: 5, name: 'Ensino Médio'},
        {id: 6, name: 'Ensino EJA'},
        {id: 7, name: 'Educação Profissional'},
        {id: 8, name: 'Educação Especial Exclusiva'}
    ];
    next();
}, response('arrangement'));

schoolApp.get('/integral_time', cache('15 day'), (req, res, next) => {
    req.result = [
        {id: 0, name: 'Não'},
        {id: 1, name: 'Sim'},
        {id: 2, name: 'Não se aplica - Semipresencial e EaD.'}
    ];
    next();
}, response('integral_time'));


rqf.addField({
    name: 'filter',
    field: false,
    where: true
}).addValue({
    name: 'id',
    table: 'escola',
    tableField: 'id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    }
}).addValue({
    name: 'city',
    table: 'municipio',
    tableField: ['nome', 'id'],
    resultField: ['city_name', 'city_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'municipio_id',
        table: 'escola'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'state',
    table: 'estado',
    tableField: ['nome', 'id'],
    resultField: ['state_name', 'state_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'estado_id',
        table: 'escola'
    },
    join: {
        primary: 'id',
        foreign: 'estado_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'year',
    table: 'escola',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '=',
        type: 'integer',
        field: 'ano_censo',
        table: 'escola'
    }
}).addField({
    name: 'search',
    field: true,
    where: true
}).addValueToField({
    name: 'city_name',
    table: 'municipio',
    tableField: 'nome',
    resultField: 'city_name',
    dontGroup: true,
    where: {
        relation: 'LIKE',
        type: 'string',
        field: 'nome'
    },
    join: {
      primary: 'id',
      foreign: 'municipio_id',
      foreignTable: 'escola'
    }
}, 'search')
.addValueToField({
    name: 'state_name',
    table: 'estado',
    tableField: 'nome',
    resultField: 'state_name',
    dontGroup: true,
    where: {
        relation: 'LIKE',
        type: 'string',
        field: 'sigla'
    },
    join: {
      primary: 'id',
      foreign: 'estado_id',
      foreignTable: 'escola'
    }
}, 'search').addValue({
    name: 'diff_location',
    table: 'escola',
    tableField: 'localizacao_diferenciada_par',
    resultField: 'diff_location_id_par',
    where: {
        relation: '=',
        type: 'integer',
        field: 'localizacao_diferenciada_par'
    }
});

rqfCount.addField({
    name: 'filter',
    field: false,
    where: true
}).addField({
    name: 'dims',
    field: true,
    where: false
}).addValue({
    name: 'id',
    table: 'escola',
    tableField: 'id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    }
}).addValueToField({
    name: 'city',
    table: 'municipio',
    tableField: ['nome', 'id'],
    resultField: ['city_name', 'city_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'municipio_id',
        table: 'escola'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'escola'
    }
}, 'dims').addValueToField({
    name: 'city',
    table: 'municipio',
    tableField: 'nome',
    resultField: 'city_name',
    where: {
        relation: '=',
        type: 'integer',
        field: 'municipio_id',
        table: 'escola'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'escola'
    }
}, 'filter').addValue({
    name: 'state',
    table: 'estado',
    tableField: ['nome', 'id'],
    resultField: ['state_name', 'state_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'estado_id',
        table: 'escola'
    },
    join: {
        primary: 'id',
        foreign: 'estado_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'mesoregion',
    table: 'municipio',
    tableField: ['nome_mesorregiao', 'mesorregiao_id'],
    resultField: ['mesoregion_name', 'mesoregion_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'mesorregiao_id',
        table: 'municipio'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'microregion',
    table: 'municipio',
    tableField: ['nome_microrregiao', 'microrregiao_id'],
    resultField: ['microregion_name', 'microregion_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'microrregiao_id',
        table: 'municipio'
    },
    join: {
        primary: 'id',
        foreign: 'municipio_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'region',
    table: 'regiao',
    tableField: ['nome', 'id'],
    resultField: ['region_name', 'region_id'],
    where: {
        relation: '=',
        type: 'integer',
        field: 'id'
    },
    join: {
        primary: 'id',
        foreign: 'regiao_id',
        foreignTable: 'escola'
    }
}).addValue({
    name: 'year',
    table: 'escola',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '=',
        type: 'integer',
        field: 'ano_censo',
        table: 'escola'
    }
}).addValue({
    name: 'location',
    table: 'escola',
    tableField: 'localizacao_id',
    resultField: 'location_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'localizacao_id'
    }
}).addValue({
    name: 'diff_location',
    table: 'escola',
    tableField: 'localizacao_diferenciada_par',
    resultField: 'diff_location_id_par',
    where: {
        relation: '=',
        type: 'integer',
        field: 'localizacao_diferenciada_par'
    }
}).addValue({
    name: 'rural_location',
    table: 'escola',
    tableField: 'localidade_area_rural',
    resultField: 'rural_location_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'localidade_area_rural'
    }
}).addValue({
    name: 'arrangement',
    table: 'escola',
    tableField: 'arranjo',
    resultField: 'arrangement_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'arranjo'
    }
}).addValue({
    name: 'adm_dependency',
    table: 'escola',
    tableField: 'dependencia_adm_id',
    resultField: 'adm_dependency_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'dependencia_adm_id'
    }
}).addValue({
    name: 'adm_dependency_detailed',
    table: 'escola',
    tableField: 'dependencia_adm_priv',
    resultField: 'adm_dependency_detailed_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'dependencia_adm_priv'
    }
}).addValue({
    name: 'government_agreement',
    table: 'escola',
    tableField: 'dependencia_convenio_publico',
    resultField: 'government_agreement_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'conveniada_pp'
    }
}).addValue({
    name: 'integral_time',
    table: 'escola',
    tableField: 'tempo_integral',
    resultField: 'integral_time_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'tempo_integral'
    }
}).addValue({
    name: 'agreement',
    table: 'escola',
    tableField: 'tipo_convenio_pp',
    resultField: 'agreement_id',
    where: {
        relation: '=',
        type: 'integer',
        field: 'tipo_convenio_pp'
    }
}).addValue({
    name: 'education_day_care_child',
    table: 'escola',
    tableField: 'reg_infantil_creche_t1',
    resultField: 'education_day_care_child_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'reg_infantil_creche_t1'
    }
}).addValue({
    name: 'education_preschool_child',
    table: 'escola',
    tableField: 'reg_infantil_preescola_t1',
    resultField: 'education_preschool_child_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'reg_infantil_preescola_t1'
    }
}).addValue({
    name: 'education_begin_elementary_school',
    table: 'escola',
    tableField: 'reg_fund_ai_t1',
    resultField: 'education_begin_elementary_school_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'reg_fund_ai_t1'
    }
}).addValue({
    name: 'education_end_elementary_school',
    table: 'escola',
    tableField: 'reg_fund_af_t1',
    resultField: 'education_end_elementary_school_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'reg_fund_af_t1'
    }
}).addValue({
    name: 'education_middle_school',
    table: 'escola',
    tableField: 'reg_medio_medio_t1',
    resultField: 'education_middle_school_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'reg_medio_medio_t1'
    }
}).addValue({
    name: 'education_professional',
    table: 'escola',
    tableField: 'educacao_profissional',
    resultField: 'education_professional_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'educacao_profissional'
    }
}).addValue({
    name: 'education_eja',
    table: 'escola',
    tableField: 'ensino_eja',
    resultField: 'education_eja_id',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'ensino_eja'
    }
}).addValue({
    name: 'min_year',
    table: 'escola',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '>=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'max_year',
    table: 'escola',
    tableField: 'ano_censo',
    resultField: 'year',
    where: {
        relation: '<=',
        type: 'integer',
        field: 'ano_censo'
    }
}).addValue({
    name: 'school_building',
    table: 'escola',
    tableField: 'local_func_predio_escolar',
    resultField: 'school_building',
    where: {
        relation: '=',
        type: 'boolean',
        field: 'local_func_predio_escolar'
    }
});
schoolApp.get('/', rqf.parse(), rqf.build(), (req, res, next) => {

    req.sql.from('escola')
        .field('escola.id')
        .field('escola.ano_censo', 'year')
        .field('escola.nome_escola', 'name')
        .field('escola.estado_id', 'state_id')
        .field('escola.municipio_id', 'city_id');
    next();
}, query, response('school'));

schoolApp.get('/count', cache('15 day'), rqfCount.parse(), (req, res, next) => {
	let arrang = ["arranjo_creche", "arranjo_pre", "arranjo_fundamental_ai", "arranjo_fundamental_af", "arranjo_multietapa", "arranjo_ensino_medio", "ensino_eja", "educacao_profissional", "ensino_especial"];

    req.sql.from('escola')
        .field('COUNT(escola.id)', 'total')
        .field("'Brasil'", 'name')
        .field('escola.ano_censo', 'year')
        .group('escola.ano_censo')
        .order('escola.ano_censo')
        .where('escola.situacao_funcionamento_pareada = 1 AND (escola.ensino_regular = 1 OR escola.ensino_eja=1 or escola.educacao_profissional=1)')

	//Transforma a query em OR se tiver o filtro do arranjo
	if (req.filter.arrangement) {
		let arrangementQuery = "";
		for (let i = 0; i < req.filter.arrangement.length - 1; i++) {
			arrangementQuery += 'escola.' + arrang[req.filter.arrangement[i]] + ' = 1 OR ';
		}
		// o ultimo elemento precisa ser sem o OR
		arrangementQuery += 'escola.' + arrang[req.filter.arrangement[req.filter.arrangement.length - 1]] + ' = 1';
		req.sql.where('' + arrangementQuery);
	}
	delete req.filter.arrangement
    next();
}, rqfCount.build(), query, id2str.transform(), addMissing(rqfCount), response('school'));

module.exports = schoolApp;