﻿"use strict";

const SORT_PROPERTY = {
    COURSE_DATE: "date",
    COURSE_TITLE: "title",
    COURSE_ID: "name"
};

const SORT_DIRECTION = {
    ASCENDING: "ascending",
    DESCENDING: "descending"
};

foraAsaApp.controller("CatalogController",
    function ($scope) {

        $scope.initCatalog = function () {

            $scope.sortedCategoryItems = [];
            $scope.isLoadingCategories = true;

            $scope.sortedCourseIds = [];
            $scope.isLoadingCourses = true;

            $scope.shoppingCartTextDefinitions = shoppingCartTextDefinitions;

            $scope.activeSortProperty = SORT_PROPERTY.COURSE_DATE;
            $scope.activeSortDirection = SORT_DIRECTION.ASCENDING;

            $scope.coursesPerPage = 10;
            $scope.courseLimit = 30;
            $scope.totalCourses = 0;

            ///////////////////////////////////////

            $scope.loadAndSortCategories();

            /////////////////////////////////

            $scope.sortedCourseIds = sortedCourseIds;
            $scope.isLoadingCourses = false;

            $scope.totalCourses = sortedCourseIds.length;

            $scope.currentSortProperty = SORT_PROPERTY.COURSE_DATE;
            $scope.sortCourses();

            if ($scope.totalCourses < $scope.courseLimit) {
                $scope.courseLimit = $scope.totalCourses;
            }
        }

        /////////////////////////////////////////////////////////////////////
        $scope.renderMore = function () {
            $scope.courseLimit = $scope.courseLimit + $scope.coursesPerPage;
            $scope.sortCourses();
            if ($scope.courseLimit > $scope.totalCourses) {
                $scope.courseLimit = $scope.totalCourses;
            }
        }

        $scope.renderAll = function () {
            $scope.courseLimit = $scope.totalCourses;
            $scope.sortCourses();
        }

        /////////////////////////////////////////////////////////////////////
        $scope.scrlTop = function () {
            $([document.documentElement, document.body]).animate({
                scrollTop: $(".navbar").offset().top
            }, 500);
        }

        /////////////////////////////////////////////////////////////////////

        $scope.setSortProperty = function (sortPropertyName) {

            if ($scope.activeSortProperty == sortPropertyName) {
                // Currently active sort property selected - just reverse order
                $scope.sortedCourseIds.reverse();

                // Update css class on button
                if ($scope.activeSortDirection === SORT_DIRECTION.ASCENDING) {
                    $scope.activeSortDirection = SORT_DIRECTION.DESCENDING;
                    $(".cs" + sortPropertyName).removeClass("ascend");
                    $(".cs" + sortPropertyName).addClass("descend");
                }
                else {
                    $scope.activeSortDirection = SORT_DIRECTION.ASCENDING;
                    $(".cs" + sortPropertyName).removeClass("descend");
                    $(".cs" + sortPropertyName).addClass("ascend");
                }
            }
            else {
                $scope.activeSortDirection = SORT_DIRECTION.ASCENDING; // Always switch to ascending when choosing a different sort property
                $scope.activeSortProperty = sortPropertyName;

                // Update css classes on buttons
                $(".cs" + sortPropertyName).removeClass("descend");
                $(".cs" + sortPropertyName).addClass("ascend");

                $(".courseSorting *").removeClass("active");
                $(".cs" + sortPropertyName).addClass("active");

                $scope.sortCourses();
            }
        }

        /////////////////////////////////////////////////////////////////////
        $scope.sortCourses = function () {

            const urlParams = new URLSearchParams(window.location.search);

            if (urlParams.has('course')) {
                return; // We are viewing a single course and don't need to sort any course list
            }

            let sortableCourses = [];

            // Create sortable array from JSON course data 
            for (const courseId of sortedCourseIds) {
                try {
                    sortableCourses.push({
                        "id": catalogCourses[courseId].No,
                        "title": catalogCourses[courseId].Title,
                        "sortDate": $scope.stringToSortableDate(courseDates[courseId].sortDate)
                    });
                }
                catch (error) {
                    // Handle silently and don't output to console - this will happen regularly in production and is harmless
                }
            }

            // Perform the actual sorting depending on the active sort property
            switch ($scope.activeSortProperty) {
                case SORT_PROPERTY.COURSE_TITLE: sortableCourses.sort((a, b) => (String(a.title)).localeCompare(String(b.title), "da"));
                    break;

                case SORT_PROPERTY.COURSE_ID: sortableCourses.sort((a, b) => (String(a.id)).localeCompare(String(b.id), "da"));
                    break;

                case SORT_PROPERTY.COURSE_DATE: sortableCourses.sort((a, b) => (String(a.sortDate)).localeCompare(String(b.sortDate), "da"));
                    break;

                default:
                    // TODO: log error in Umbraco log
                    break;
            }

            let newSortedCourseIds = [];

            for (const sortableCourse of sortableCourses) {
                newSortedCourseIds.push(sortableCourse.id);
            }

            $scope.sortedCourseIds = newSortedCourseIds;

            if ($scope.courseLimit > $scope.totalCourses) {
                $scope.courseLimit = $scope.totalCourses;
            }
        }

        /////////////////////////////////////////////////////////////////////
        $scope.stringToSortableDate = function (originalDateString) {
            const dateStringParts = originalDateString.split(" ");
            const year = String(dateStringParts[2].trim());
            const dayAndMonth = dateStringParts[1].split("/");
            const dayOfMonth = String(dayAndMonth[0]).padStart(2, '0');
            const month = String(dayAndMonth[1]).padStart(2, '0');

            return year + month + dayOfMonth;
        }

        /////////////////////////////////////////////////////////////////////
        $scope.loadAndSortCategories = function () {
            const unsortedCategoryItems = JSON.parse(JSON.stringify(categoryItems));

            for (const categoryID in sortedCategoryNodeIDs)
                for (const item in unsortedCategoryItems) {
                    const categoryItem = unsortedCategoryItems[item];

                    if (categoryItem.ID === categoryID) {
                        $scope.sortedCategoryItems.push(categoryItem);
                        delete unsortedCategoryItems[item];
                    }
                }

            for (const item in unsortedCategoryItems) {
                const categoryItem = unsortedCategoryItems[item];
                $scope.sortedCategoryItems.push(categoryItem);
            }

            $scope.isLoadingCategories = false;
        }
    })