/*
Copyright (C) 2016 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 libs = `${process.cwd()}/libs`;
const gender = require(`${libs}/convert/gender`);
const period = require(`${libs}/convert/period`);
const schoolYear = require(`${libs}/convert/schoolYear`);
const admDependency = require(`${libs}/convert/admDependency`);
const admDependencyPriv = require(`${libs}/convert/admDependencyPriv`);
const location = require(`${libs}/convert/location`);
const ruralLocation = require(`${libs}/convert/ruralLocation`);
const ethnicGroup = require(`${libs}/convert/ethnicGroup`);
const ethnicGroupIES = require(`${libs}/convert/ethnicGroupIES`);
const agreement = require(`${libs}/convert/agreement`);
const booleanVariable = require(`${libs}/convert/booleanVariable`);
const educationLevel = require(`${libs}/convert/educationLevel`);
const educationLevelMod = require(`${libs}/convert/educationLevelMod`);
const educationLevelShort = require(`${libs}/convert/educationLevelShort`);
const educationType = require(`${libs}/convert/educationType`);
const citySize = require(`${libs}/convert/citySize`);
const incomeLevel = require(`${libs}/convert/incomeLevel`);
const idhmLevel = require(`${libs}/convert/idhmLevel`);
const stateName = require(`${libs}/convert/stateName`);
const contractType = require(`${libs}/convert/contractType`);
const ethnicGroupPnad = require(`${libs}/convert/ethnicGroupPnad`);
const ageRange = require(`${libs}/convert/ageRange`);
const ageRangeAll = require(`${libs}/convert/ageRangeAll`);
const fullAgeRange = require(`${libs}/convert/fullAgeRange`);
const genderPnad = require(`${libs}/convert/genderPnad`);
const fifthHouseholdIncome = require(`${libs}/convert/fifthHouseholdIncome`);
const extremesHouseholdIncome = require(`${libs}/convert/extremesHouseholdIncome`);
const educationLevelBasic = require(`${libs}/convert/educationLevelBasic`);
const useTransport = require(`${libs}/convert/booleanVariable`);
const useTransportPublic = require(`${libs}/convert/booleanVariable`);
const transportationManager = require(`${libs}/convert/transportationManager`);
const specialClass = require(`${libs}/convert/booleanVariable`);
const integralTime = require(`${libs}/convert/integralTime`);
const educationLevelSchoolYear = require(`${libs}/convert/educationLevelSchoolYear`);
const pfe = require(`${libs}/convert/pfe`);
const upperAdmDependency = require(`${libs}/convert/upperAdmDependency`);
const academicOrganization = require(`${libs}/convert/academicOrganization`);
const ocdeSpecific = require(`${libs}/convert/ocdeSpecific`);
const ocdeGeral = require(`${libs}/convert/ocdeGeral`);
const ocdeDetailed = require(`${libs}/convert/ocdeDetailed`);
const academicLevel = require(`${libs}/convert/academicLevel`);
const upperEducationMod = require(`${libs}/convert/upperEducationMod`);
const studentDeficiency = require(`${libs}/convert/studentDeficiency`);
const schoolType = require(`${libs}/convert/schoolType`);
const upperTurn = require(`${libs}/convert/upperTurn`);
const teacherSituation = require(`${libs}/convert/teacherSituation`);
const workRegime = require(`${libs}/convert/workRegime`);
const substitute = require(`${libs}/convert/booleanVariable`);
const visitor = require(`${libs}/convert/booleanVariable`);
const eadTeacher = require(`${libs}/convert/booleanVariable`);
const graduationPresential = require(`${libs}/convert/booleanVariable`);
const postgraduateEadTeacher = require(`${libs}/convert/booleanVariable`);
const postgraduatePresentialTeacher = require(`${libs}/convert/booleanVariable`);
const teacherSchooling = require(`${libs}/convert/teacherSchooling`);
const ethnicGroupTeacherIES = require(`${libs}/convert/ethnicGroupTeacherIES`);
const genderIES = require(`${libs}/convert/genderIES`);
const deficiency = require(`${libs}/convert/booleanVariable`);

const ids = {
    gender_id: gender,
    period_id: period,
    school_year_id: schoolYear,
    education_level_id: educationLevel,
    education_level_basic_id: educationLevelBasic,
    education_level_mod_id: educationLevelMod,
    education_level_short_id: educationLevelShort,
    adm_dependency_id: admDependency,
    adm_dependency_detailed_id: admDependencyPriv,
    location_id: location,
    rural_location_id: ruralLocation,
    location_detailed_id: ruralLocation,
    ethnic_group_id: ethnicGroup,
    agreement_id: agreement,
    integral_time_id: integralTime,
    government_agreement_id: booleanVariable,
    education_day_care_child_id: booleanVariable,
    education_preschool_child_id: booleanVariable,
    education_begin_elementary_school_id: booleanVariable,
    education_end_elementary_school_id: booleanVariable,
    education_middle_school_id: booleanVariable,
    education_professional_id: booleanVariable,
    education_eja_id: booleanVariable,
    education_type_id: educationType,
    income_level_id: incomeLevel,
    city_size_id: citySize,
    idhm_level_id: idhmLevel,
    state_id: stateName,
    contract_type_id: contractType,
    ethnic_group_pnad_id: ethnicGroupPnad,
    age_range_id: ageRange,
    age_range_all_id: ageRangeAll,
    full_age_range_id: fullAgeRange,
    gender_pnad_id: genderPnad,
    fifth_household_income_id: fifthHouseholdIncome,
    extremes_household_income_id: extremesHouseholdIncome,
    use_transport_id: useTransport,
    use_transport_public_id: useTransportPublic,
    transportation_manager_id: transportationManager,
    special_class_id: specialClass,
    education_level_school_year_id: educationLevelSchoolYear,
    pfe_id: pfe,
    upper_adm_dependency_id: upperAdmDependency,
    academic_organization_id: academicOrganization,
    ocde_specific_id: ocdeSpecific,
    ocde_geral_id: ocdeGeral,
    ocde_detailed_id: ocdeDetailed,
    academic_level_id: academicLevel,
    upper_education_mod_id: upperEducationMod,
    student_deficiency_id: studentDeficiency,
    school_type_id: schoolType,
    upper_turn_id: upperTurn,
    is_free_id: booleanVariable,
    night_time_id: booleanVariable,
    capital_id: booleanVariable,
    ethnic_group_ies_id: ethnicGroupIES,
    teacher_situation_id: teacherSituation,
    work_regime_id: workRegime,
    substitute_id: booleanVariable,
    visitor_id: booleanVariable,
    ead_teacher_id: eadTeacher,
    graduation_presential_id: graduationPresential,
    postgraduate_ead_teacher_id: postgraduateEadTeacher,
    postgraduate_presential_teacher_id: postgraduatePresentialTeacher,
    teacher_schooling_id: teacherSchooling,
    ethnic_group_teacher_ies_id: ethnicGroupTeacherIES,
    gender_ies_id: genderIES,
    deficiency_id: deficiency
};

function transform(removeId=false) {
    return (req, res, next) => {
        if(req.result.length <= 0) {
            return next();
        }
        // Para cada objeto do resultado
        req.result.forEach((obj) => {
            Object.keys(obj).forEach((key) => {
                // Se não há uma função especificada, retorna
                if(typeof ids[key] === 'undefined') return;
                let id = obj[key];
                obj[key.replace('_id', '_name')] = ids[key](id);
                if(removeId) delete obj[key];
            });
        });
        next();
    };
}

function multitransform(removeId=false) {
    return (req, res, next) => {
        Object.keys(req.result[0]).forEach((query) => {
            req.result[0][query].forEach((obj) => {
                Object.keys(obj).forEach((key) => {
                    if(typeof ids[key] === 'undefined') return;
                    let id = obj[key];
                    obj[key.replace('_id', '_name')] = ids[key](id);
                    if(removeId) delete obj[key];
                });
            })
        });
        next();
    }
}

module.exports = {
    transform,
    multitransform,
    gender,
    period,
    schoolYear,
    educationLevel,
    educationLevelBasic,
    educationLevelMod,
    educationLevelShort,
    admDependency,
    admDependencyPriv,
    location,
    ruralLocation,
    ethnicGroup,
    agreement,
    booleanVariable,
    educationType,
    incomeLevel,
    citySize,
    idhmLevel,
    stateName,
    contractType,
    ethnicGroupPnad,
    ageRange,
    ageRangeAll,
    fullAgeRange,
    genderPnad,
    fifthHouseholdIncome,
    extremesHouseholdIncome,
    useTransport,
    transportationManager,
    specialClass,
    integralTime,
    upperAdmDependency,
    academicOrganization,
    ocdeSpecific,
    ocdeGeral,
    ocdeDetailed,
    academicLevel,
    upperEducationMod,
    studentDeficiency,
    schoolType,
    ethnicGroupIES,
    upperTurn,
    teacherSituation,
    workRegime,
    substitute,
    visitor,
    eadTeacher,
    graduationPresential,
    postgraduateEadTeacher,
    postgraduatePresentialTeacher,
    teacherSchooling,
    ethnicGroupTeacherIES,
    genderIES,
    deficiency
};