﻿"use strict";

foraAsaApp.controller("ShoppingCartController",
    function ($scope, $rootScope, shoppingCartService, checkoutService, configService) {

        $scope.courseNo = null;
        $scope.quantity = null;
        $scope.waitingListNotification = '';
        $scope.availableSeats = [];
        $scope.isLoading = true;
        $scope.title = '';
        $scope.errorMsg = '';

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Initialize controller with details for the currently selected course
        $scope.init = function () {

            $scope.errorMsg = '';
            $scope.courseNo = angular.element(document.querySelector(configService.htmlSelectorKurvCourseId)).val();
            $scope.title = angular.element(document.querySelector(configService.htmlSelectorTitle)).text();

            shoppingCartService.QueryShoppingCartTextDefinitions()
                .then(function (response) {
                    $scope.shoppingCartTextDefinitions = response.data.shoppingCartTextDefinitions;
                    $scope.GetCourseConditions();
                    $scope.QueryHoldStatusText();
                },
                    function (data) {
                        // TODO: handle error here
                    }
                );
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Read conditions for the currently selected course
        $scope.GetCourseConditions = function () {

            checkoutService.GetCourseConditions($scope.courseNo, 0)
                .then(function (response) {

                    if (response.data.Status === 1) {
                        $scope.conditions = response.data;
                        $scope.availableSeats = $scope.GetAvailableSeatsTextArray(response.data.AvailableSeats);
                        $scope.quantity = $scope.availableSeats[0];
                        $scope.ShowWaitingListNotification();
                        $scope.isLoading = false;
                    }
                    else {
                        // TODO: log from Umbraco
                        console.error("Call to CheckoutService failed: " + JSON.stringify(response));
                        $scope.isLoading = false;
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                    }
                },
                    function (data) {
                        // TODO: log from Umbraco
                        console.error("Call to CheckoutService failed: " + JSON.stringify(data));
                        $scope.isLoading = false;
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                    }
                );
        }

        $scope.QueryHoldStatusText = function () {
            shoppingCartService.QueryHoldStatusTextLive($scope.courseNo)
                .then(function (response) {

                    if (response.data.Status === 1) {
                        $scope.courseStatusText = response.data.CourseStatusText;
                    }
                    else {
                        console.error("Call to CheckoutService failed: " + JSON.stringify(response));
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                    }
                },
                    function (data) {
                        // TODO: log from Umbraco
                        console.error("Call to CheckoutService failed: " + JSON.stringify(data));
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                    }
                );
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Create notification text for waiting list. Empty string if all required seats available
        $scope.ShowWaitingListNotification = function () {

            if ($scope.quantity.Value > $scope.conditions.AvailableSeats) {
                if ($scope.conditions.AvailableSeats > 0) {
                    var qtyWaitingList = $scope.quantity.Value - $scope.conditions.AvailableSeats;
                    $scope.waitingListNotification = $scope.shoppingCartTextDefinitions.waitinglistnNotice1 + " " + qtyWaitingList + " " + $scope.shoppingCartTextDefinitions.waitinglistnNotice2;
                }
                else {
                    $scope.waitingListNotification = $scope.shoppingCartTextDefinitions.waitinglistnNotice3;
                }
            }
            else {
                $scope.waitingListNotification = '';
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Add the currently selected course to the shopping cart
        $scope.AddToShoppingCart = function () {

            $scope.isLoading = true;

            if ($scope.quantity === 0 || $scope.quantity.Value === 0) {
                return;
            }

            if ($scope.conditions.IsBulk) {
                shoppingCartService.GetShoppingCart()
                    .then(function (response) {
                        if (response.data.Status === 1) {
                            var shoppingCart = response.data.ShoppingCart;
                            var cartItem = null;

                            angular.forEach(shoppingCart,
                                function (shoppingCartItem) {
                                    if (shoppingCartItem.CourseId === $scope.courseNo) {
                                        cartItem = shoppingCartItem;
                                    }
                                });

                            if (cartItem !== null) {
                                var bulkQuantity = cartItem.Qty;

                                shoppingCartService.RemoveCourse(cartItem)
                                    .then(function () {
                                        $scope.HandleReservation(bulkQuantity);
                                    },
                                        function (data) {
                                            // TODO: log from Umbraco
                                            console.error("Call to ShoppingCartService failed: " + JSON.stringify(data));
                                            $scope.errorMsg = configService.shoppingCartErrorMsg;
                                            $scope.isLoading = false;
                                        }
                                    );
                            }
                            else {
                                $scope.HandleReservation(0);
                            }
                        }
                        else {
                            // TODO: log from Umbraco
                            console.error("Call to CheckoutService failed: " + JSON.stringify(response));
                            $scope.errorMsg = configService.shoppingCartErrorMsg;
                            $scope.isLoading = false;
                        }
                    },
                        function (data) {
                            // TODO: log from Umbraco
                            console.error("Call to CheckoutService failed: " + JSON.stringify(data));
                            $scope.errorMsg = configService.shoppingCartErrorMsg;
                            $scope.isLoading = false;
                        }
                    );
            }
            else {
                $scope.HandleReservation(0);
            }
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Create reservations for the currently selected course
        $scope.HandleReservation = function (bulkQuantity) {

            checkoutService.CreateReservations($scope.courseNo, $scope.quantity.Value + bulkQuantity, location.href)
                .then(function (response) {
                    if (response.data.Status === 1) {
                        $scope.isLoading = false;
                        $rootScope.$broadcast('refreshShoppingCart');
                    }
                    else {
                        // TODO: log from Umbraco
                        console.error("Call to CheckoutService failed: " + JSON.stringify(response));
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                        $scope.isLoading = false;
                    }
                },
                    function (data) {
                        // TODO: log from Umbraco
                        console.error("Call to CheckoutService failed: " + JSON.stringify(data));
                        $scope.errorMsg = configService.shoppingCartErrorMsg;
                        $scope.isLoading = false;
                    }
                );
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Generate dropdown list texts from the number of available course seats
        $scope.GetAvailableSeatsTextArray = function (availableSeats) {

            var result = [];

            for (var i = 1; i <= availableSeats; i++) {
                result.push({ 'Name': i, 'Value': i });
            }

            for (var i2 = i; i2 <= i + 4; i2++) {
                if (availableSeats > 0) {
                    result.push({ 'Name': i2 + ' (' + (i2 - i + 1) + ' på venteliste)', 'Value': i2 });
                } else {
                    result.push({ 'Name': i2 + ' på venteliste', 'Value': i2 });
                }
            }

            return result;
        }

        ///////////////////////////////////////////////////////////////////////////////////////////
        // Event handler for refreshing the shopping cart contents
        $rootScope.$on('refreshShoppingCart', function () {

            $scope.isLoading = true;
            $scope.errorMsg = "";
            $scope.Participants = {};
            $scope.GetCourseConditions();
        });
    })
