/*
 * Copyright (C) 2021 Echedey López Romero <elr@disroot.org>
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <http://www.gnu.org/licenses/>.
 */

let Countries = [
    {
        'id': 'spain',
        'name': 'Spain'
    }
];

let ProvincesFilter = [
    {
        'provincia_id': '35'
    }, {
        'provincia_id': '38'
    }
];

let Provinces;
let Municipalities;
let ZIPCodes;

function GenerateFieldValues(Data, FieldName) {
    let FieldValues = [];

    Data.forEach((Value, Key) => {
        FieldValues.push(Value[FieldName]);
    });

    return FieldValues;
}

function DumpCanaryData(Data, DependentValues, FieldName, NoId = false, NewId = '') {
    let CanaryData = [];

    let FieldValues = GenerateFieldValues(DependentValues, FieldName);

    Data.forEach((Value, Key) => {
        if (FieldValues.includes(Value[FieldName])) {
            if (NoId === true && NewId !== '') {
                Value[NewId] = Key.toString();
                CanaryData.push(Value);
            } else {
                CanaryData.push(Value);
            }
        }
    });

    return CanaryData;
}

// Load data
async function LoadData() {
    await $.getJSON('./data/provincias.json', function (Data) {
        Provinces = DumpCanaryData(Data, ProvincesFilter, 'provincia_id');
    });
    await $.getJSON('./data/municipios_islas.json', function (Data) {
        Municipalities = DumpCanaryData(Data, Provinces, 'provincia_id');
    });
    await $.getJSON('./data/codigos_postales_municipios.json', function (Data) {
        ZIPCodes = DumpCanaryData(Data, Municipalities, 'municipio_id', true, 'cp_id');
    });
}
;

function CheckListValue(Data, Content, FieldName) {
    let Exists = false;

    let Position = 0;
    while (Position < Data.length && !Exists) {
        if (Data[Position][FieldName] === Content) {
            Exists = true;
        }

        Position++;
    }

    return Exists;
}

function GeneratePossibleValues(Data, Content, Name) {
    let PossibleValues = [];

    Data.forEach((Value, Key) => {
        if (Value[Name] === Content) {
            PossibleValues.push(Value);
        }
    });

    return PossibleValues;
}

function RestartZIPCode() {
    let ZIPCode = document.getElementById('zipcode');

    ZIPCode.value = '';
    ZIPCode.setAttribute('disabled', '');
}

function ShowZIPCode() {
    let Municipality = document.getElementById('municipality').value;
    let ZIPCode = document.getElementById('zipcode');

    let PossibleValues = GeneratePossibleValues(ZIPCodes, Municipality, 'municipio_id');

    if (PossibleValues.length !== 0) {
        ZIPCode.removeAttribute('disabled');

        for (let Position = 1; Position < ZIPCode.length; Position++) {
            let Option = ZIPCode[Position];
            if (CheckListValue(PossibleValues, Option.value, 'cp_id')) {
                Option.removeAttribute('style');
            } else {
                Option.style.display = 'none';
            }
        }
    } else {
        for (let Position = 1; Position < ZIPCode.length; Position++) {
            let Option = ZIPCode[Position];

            Option.removeAttribute('style');
        }
    }
}

function RestartMunicipality() {
    let Municipality = document.getElementById('municipality');

    Municipality.value = '';
    Municipality.setAttribute('disabled', '');
}

function ShowMunicipality() {
    let Province = document.getElementById('province').value;
    let Municipality = document.getElementById('municipality');

    let PossibleValues = GeneratePossibleValues(Municipalities, Province, 'provincia_id');

    if (PossibleValues.length !== 0) {
        Municipality.removeAttribute('disabled');

        for (let Position = 1; Position < Municipality.length; Position++) {
            let Option = Municipality[Position];
            if (CheckListValue(PossibleValues, Option.value, 'municipio_id')) {
                Option.removeAttribute('style');
            } else {
                Option.style.display = 'none';
            }
        }
    } else {
        for (let Position = 1; Position < Municipality.length; Position++) {
            let Option = Municipality[Position];

            Option.removeAttribute('style');
        }

    }
    
    RestartZIPCode();
    ShowZIPCode();
}

function RestartProvince() {
    let Province = document.getElementById('province');

    Province.value = '';
    Province.setAttribute('disabled', '');
}

function ShowProvince() {
    let Country = document.getElementById('country').value;
    let Province = document.getElementById('province');

    if (Country === Countries[0]['id']) {
        Province.removeAttribute('disabled');

        for (let Position = 1; Position < Province.length; Position++) {
            let Option = Province[Position];
            if (CheckListValue(Provinces, Option.value, 'provincia_id')) {
                Option.removeAttribute('style');
            } else {
                Option.style.display = 'none';
            }
        }
    } else {
        for (let Position = 1; Position < Province.length; Position++) {
            let Option = Province[Position];

            Option.removeAttribute('style');
        }
    }
    
    RestartMunicipality();
    ShowMunicipality();
}
