/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

var autofillDB = {};
var autofillStreetDB = [];

if (getStorage("autofill_db") != null) {
    autofillDB = JSON.parse(getStorage("autofill_db"));
}

if (getStorage("autofill_streetdb") != null) {
    autofillStreetDB = JSON.parse(getStorage("autofill_streetdb"));
}

function addressToNumberAndStreet(address) {
    var number = "";
    var street = "";

    var addressRegex = RegExp("^[0-9]+ .+$");
    if (addressRegex.test(address)) {
        number = address.split(" ", 2)[0];
        street = address.substring(address.indexOf(' ') + 1);
    }

    return [number, street];
}

function addAutofillEntry(address) {
    var [number, street] = addressToNumberAndStreet(address);

    if (number == "" || street == "") {
        return;
    }

    if (typeof autofillDB[number] == 'undefined') {
        autofillDB[number] = [
            [street, 1]
        ];
    } else {
        var found = false;
        for (var i = 0; i < autofillDB[number].length; i++) {
            if (autofillDB[number][i][0] == street) {
                autofillDB[number][i][1]++;
                found = true;
                break;
            }
        }

        if (!found) {
            autofillDB[number].push([street, 1]);
        }
    }

    setStorage("autofill_db", JSON.stringify(autofillDB));


    var found = false;
    for (var i = 0; i < autofillStreetDB.length; i++) {
        if (autofillStreetDB[i][0] == street) {
            autofillStreetDB[i][1]++;
            found = true;
            break;
        }
    }

    if (!found) {
        autofillStreetDB.push([street, 1]);
    }

    setStorage("autofill_streetdb", JSON.stringify(autofillStreetDB));
}

function searchAutofill(q, number) {
    var byNumber = [];
    if (typeof number != 'undefined') {
        byNumber = searchAutofillByNumber(number, q);
    }

    var byStreet = [];
    if (q.length > 0) {
        byStreet = searchAutofillByStreet(q);
    }

    return byNumber.concat(byStreet.filter((item) => byNumber.indexOf(item) < 0));
}

function searchAutofillByNumber(number, q) {
    if (typeof autofillDB[number] == 'undefined') {
        return [];
    }

    var sorted = autofillDB[number].sort(function (a, b) {
        return b[1] - a[1];
    });

    var query = false;
    if (typeof q != 'undefined' && q != "") {
        query = true;
    }

    var streets = [];

    for (var i = 0; i < sorted.length; i++) {
        // if there's no search query OR if the query matches the current item
        if (!query || (query && sorted[i][0].toLowerCase().includes(q))) {
            streets.push(sorted[i][0]);
        }
    }

    return streets;
}

function searchAutofillByStreet(q) {
    var streets = [];

    var sortedDB = autofillStreetDB.sort(function (a, b) {
        return b[1] - a[1];
    });

    //console.log(sortedDB);

    q = q.toLowerCase();

    for (var i = 0; i < sortedDB.length; i++) {
        //console.log(sortedDB[i][0].toLowerCase().indexOf(q));
        if (sortedDB[i][0].toLowerCase().includes(q)) {
            streets.push(sortedDB[i][0]);
        }
    }

    return streets;
}

function setupStreetAutofill(streetBox, numberBox) {
    app.autocomplete.create({
        inputEl: streetBox,
        openIn: 'dropdown',
        /* If we set valueProperty to "id" then input value on select will be set according to this property */
        valueProperty: 'name', //object's "value" property name
        textProperty: 'name', //object's "text" property name
        limit: 10, //limit to 10 results
        typeahead: true,
        dropdownPlaceholderText: '',
        source: function (query, render) {
            var streets = searchAutofill(query, $(numberBox).val());
            render(streets);
        }
    });
}