/*
 * 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/.
 */

if (inStorage("notes")) {
    var notes = JSON.parse(getStorage("notes"));
} else {
    var notes = [];
    setStorage("notes", "[]");
}

function findNote(number, street) {
    for (i in notes) {
        if (notes[i].number == number && notes[i].street.toUpperCase() == street.toUpperCase()) {
            return notes[i];
        }
    }
    return null;
}

function isDeliverable(number, street) {
    var note = findNote(number, street);

    var ok = true;
    var reason = "";

    if (note != null) {
        for (t in note.toggles) {
            if (!note.toggles.hasOwnProperty(t)) {
                continue;
            }

            for (tt in SETTINGS.routenotetoggles) {
                if (SETTINGS.routenotetoggles[tt].id == t) {
                    if (SETTINGS.routenotetoggles[tt].preventsDelivery == true && note.toggles[t] == true) {
                        ok = false;
                        reason = SETTINGS.routenotetoggles[tt].reason;
                    }
                }
            }
        }
    }

    return {
        ok: ok,
        reason: reason
    };
}

function saveNote(id) {
    var exists = false;
    var index = -1;
    for (var i = 0; i < notes.length; i++) {
        if (notes[i].id == id) {
            exists = true;
            index = i;
        }
    }

    var note = {
        id: id,
        number: "",
        street: "",
        zipcode: "",
        route: "",
        notes: "",
        toggles: {}
    };
    if (exists) {
        note = notes[index];
    }

    note.number = $("input[name=number]").val().trim();
    note.street = $("input[name=street]").val().trim();
    note.zipcode = $("input[name=zipcode]").val().trim();
    note.route = $("input[name=route]").val().trim().toUpperCase();
    note.notes = $("textarea#notes").val().trim();

    if (note.number == "") {
        app.dialog.alert("Fill in an address number.", "Error");
        return false;
    }
    if (note.street == "") {
        app.dialog.alert("Fill in a street.", "Error");
        return false;
    }
    if (note.zipcode == "") {
        app.dialog.alert("Fill in a zip code.", "Error");
        return false;
    }
    if (note.route == "" || /^[CRHG][0-9]{3}$/.test(note.route) != true) {
        app.dialog.alert("Fill in a route (examples: C123, R001, H050).", "Error");
        return false;
    }

    setStorage("lastrouteid", note.route);
    setStorage("zipcode", note.zipcode);

    for (i in SETTINGS.routenotetoggles) {
        var toggle = SETTINGS.routenotetoggles[i];
        note.toggles[toggle.id] = $(".note-toggle[data-id=" + toggle.id + "]").is(":checked");
    }
    if (exists) {
        notes[index] = note;
    } else {
        notes.push(note);
    }


    setStorage("notes", JSON.stringify(notes));

    if (exists) {
        appendActivityLog("Edited note", note.number + " " + note.street, "", "fas fa-sticky-note");
    } else {
        appendActivityLog("Added note", note.number + " " + note.street, "", "fas fa-sticky-note");
    }

    app.toast.show({
        text: "<i class='fas fa-check'></i> Note saved!",
        position: "bottom",
        destroyOnClose: true,
        closeTimeout: 1000 * 3
    });
}

function deleteNote(id) {
    var note = {};
    for (var i = 0; i < notes.length; i++) {
        if (notes[i].id == id) {
            note = notes[i];
            notes.splice(i, 1);
        }
    }
    setStorage("notes", JSON.stringify(notes));
    appendActivityLog("Deleted note", note.number + " " + note.street, "", "fas fa-sticky-note");
}

$(".view-main").on("click", "#savenotebtn", function () {
    saveNote($(this).data("noteid"));
});

$(".view-main").on("click", ".editnotebtn", function () {
    var noteid = $(this).data("noteid");

    var note = {};
    for (var i = 0; i < notes.length; i++) {
        if (notes[i].id == noteid) {
            note = notes[i];
        }
    }

    var toggles = [];
    for (t in SETTINGS.routenotetoggles) {
        var toggle = SETTINGS.routenotetoggles[t];
        toggles.push({
            id: toggle.id,
            name: toggle.name,
            checked: note.toggles[toggle.id] == true
        });
    }

    router.navigate("/myroute/editnote", {
        context: {
            title: "Edit Note",
            toggles: toggles,
            noteid: noteid,
            note: note
        }
    });
});

$(".view-main").on("click", ".deletenotebtn", function () {
    var noteid = $(this).data("noteid");
    app.dialog.confirm("Delete note?", "Confirm", function () {
        deleteNote(noteid);
        router.navigate("/myroute", {
            reloadCurrent: true
        })
    });
});

$(".view-main").on("blur", "#notenumberinput,#notestreetinput", function () {
    if (findNote($("#notenumberinput").val(), $("#notestreetinput").val()) != null) {
        app.dialog.alert("A note already exists for that address.", "Warning");
    }
});

/*
 * Save note with Ctrl-S
 */
$(".view-main").on("keydown", ".page[data-name=editnote]", function (event) {
        if (event.ctrlKey || event.metaKey) {
            switch (String.fromCharCode(event.which).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    saveNote($("#savenotebtn").data("noteid"));
                    break;
            }
        }
    });

function getToggleName(id) {
    for (i in SETTINGS.routenotetoggles) {
        if (SETTINGS.routenotetoggles[i].id == id) {
            return SETTINGS.routenotetoggles[i].name;
        }
    }
    return "";
}

function getToggleIcon(id) {
    for (i in SETTINGS.routenotetoggles) {
        if (SETTINGS.routenotetoggles[i].id == id) {
            return SETTINGS.routenotetoggles[i].icon;
        }
    }
    return "";
}

Template7.registerHelper('notetogglename', function (key) {
    return getToggleName(key);
});

Template7.registerHelper('notetoggleicon', function (key) {
    return getToggleIcon(key);
});

Template7.registerHelper('newlinestobr', function (text) {
    return text.replace(/(?:\r\n|\r|\n)/g, '<br>');
});