LL.controller = {
    getLanguages: function () {
        return new Promise(function (resolve, reject) {
            if (window.AndroidInterface !== undefined) {
                if (window.AndroidInterface.isServerAvailable()) {
                    LL.api.getLanguages().then(function (json) {
                        if (window.AndroidInterface.updateLanguages(JSON.stringify(json))) {
                            console.info("languages updated on the phone");
                        } else {
                            console.error("unable to update languages on the phone");
                        }

                        if (json.languages !== undefined) {
                            resolve(json.languages);
                        } else {
                            reject("Bad format");
                        }
                    })
                } else {
                    var json = window.AndroidInterface.getLanguages();

                    if (json.languages !== undefined) {
                        resolve(json.languages);
                    } else {
                        reject("Bad format");
                    }
                }
            } else {
                LL.api.getLanguages().then(function (json) {
                    if (json.languages !== undefined) {
                        resolve(json.languages);
                    } else {
                        reject("Bad format");
                    }
                });
            }
        });
    },
    getActivities: function () {
        return new Promise(function (resolve, reject) {
            if (window.AndroidInterface !== undefined) {
                if (window.AndroidInterface.isServerAvailable()) {
                    LL.api.getActivities().then(function (json) {
                        if (json.activities !== undefined) {
                            if (window.AndroidInterface.updateActivities(JSON.stringify(json))) {
                                console.info("activities updated on the phone");
                            } else {
                                console.error("unable to update activities on the phone");
                            }

                            resolve(json.activities);
                        } else {
                            reject("Bad format");
                        }
                    });
                } else {
                    var json = JSON.parse(window.AndroidInterface.getActivities());

                    if (json.activities !== undefined) {
                        resolve(json.activities);
                    } else {
                        reject("Bad format");
                    }
                }
            } else {
                LL.api.getActivities().then(function (json) {
                    if (json.activities !== undefined) {
                        resolve(json.activities);
                    } else {
                        reject("Bad format");
                    }
                });
            }
        });
    },
    getSavedLessons: function () {
        return new Promise(function (resolve, reject) {
            if (window.AndroidInterface !== undefined) {
                if (!window.AndroidInterface.isServerAvailable()) {
                    var savedLessons = window.AndroidInterface.getSavedLessons();

                    resolve(savedLessons);
                }
            }

            LL.api.getSavedLessons({limit: 10}).then(function (json) {
                resolve(json.savedLessons);
            }, reject);
        })
    },
    deleteSavedLesson: function (id) {
        return new Promise(function (resolve, reject) {
            if (window.AndroidInterface !== undefined) {
                if (window.AndroidInterface.deleteSavedLesson(id)) {
                    console.log("delete saved lesson on the phone");
                }
                else {
                    console.log("unable to delete saved lesson on the phone.");

                    reject();
                }

                if (!window.AndroidInterface.isServerAvailable()) {
                    resolve();
                }
            }

            LL.api.deleteSavedLessonUser({id: id}).then(resolve, reject);
        });
    },
    getDifficulties: function () {
        return new Promise(function (resolve, reject) {
            LL.api.resultUser({order: -1, limit: 10}).then(function (json) {
                resolve(json.result);
            }, reject);
        });
    },
    createLessonUser: function () {
        return new Promise(function (resolve, reject) {
            //retrieve data
            var languages = document.getElementById("select-languages").value;
            var languagesSplit = languages.split("|");

            var activities = [];

            var activitiesDiv = document.getElementById("activities-div").getElementsByTagName("input");

            for (let i = 0; i < activitiesDiv.length; i++) {
                if (activitiesDiv[i].checked) {
                    activities.push(activitiesDiv[i].name);
                }
            }

            var parameters = {
                language1: languagesSplit[0],
                language2: languagesSplit[1],
                duration: document.getElementById("number-input-duration").value,
                activities: activities
            };

            LL.data.favoriteStart.save(languages, parameters.duration, parameters.activities);

            //create lesson on server
            LL.api.createLessonUser(parameters).then(function (json) {
                try {
                    var lesson = json.lesson;

                    console.log("lesson", lesson);

                    if (lesson.questions.length < 1) {
                        $.notify("Unable to find questions for your lesson.", {showDuration: 1000});
                    } else {
                        if (window.AndroidInterface !== undefined) {
                            if (window.AndroidInterface.saveLesson(JSON.stringify(lesson))) {
                                console.log("saved lesson on the phone");
                            }
                            else {
                                console.log("unable to save the lesson on the phone")
                            }
                        }

                        resolve(lesson);
                    }
                }
                catch (e) {
                    $.notify("Unable to load the lesson: " + e.message, {showDuration: 1000});

                    reject();
                }
            }, reject);
        });
    },
    startLessonUser: function (id) {
        return new Promise(function (resolve, reject) {
            if (window.AndroidInterface !== undefined) {
                if (!window.AndroidInterface.isServerAvailable()) {
                    var savedLessons = window.AndroidInterface.getSavedLessons();

                    for (var i = 0; i < savedLessons.length; i++) {
                        if (savedLessons[i].id === id) {
                            resolve(savedLessons[i]);
                        }
                    }

                    $.notify("Unable to find this lesson on the phone.", {showDuration: 1000});

                    reject();
                }
            }

            LL.api.startLessonUser({id: id}).then(function (json) {
                resolve(json.lesson);
            });
        });
    },
    existsUser: function (username) {
        return new Promise(function (resolve) {
            LL.api.existsUser({username: username}).then(function (json) {
                resolve(json.existsUser);
            });
        });
    },
    connectUser: function (username, password) {
        var parameters = {};

        if (password === undefined) {
            parameters.key = username;
        }
        else {
            parameters.username = username;
            parameters.password = password;
        }

        LL.api.connectUser(parameters).then(function (json) {
            if (json.key !== undefined) {
                LL.data.key.save(json.key);
            }

            LL.interface.displayLoggedInterface();
        });
    },
    autoConnectUser: function () {
        if (LL.data.key.exists()) {
            var key = LL.data.key.get();

            console.log("trying to sign-in with key", key);

            if (window.AndroidInterface !== undefined) {
                console.log("trying offline login from phone");

                if (window.AndroidInterface.offlineLogin()) {
                    console.log("offline logged");

                    LL.interface.displayLoggedInterface();
                }
                else {
                    console.log("finally using online login");

                    LL.controller.connectUser(key)
                }
            }
            else {
                LL.controller.connectUser(key);
            }
        }
    }
};