app.controller('HomeController', ['$scope', '$http', 'courseFactory','$resource',
    function ($scope, $http, courseFactory,$resource) {
        $scope.baseUrl = appUrl;

        $scope.availableTerms = {}; // Terms available to select
        $scope.selectedTerm = "";
        $scope.terms = [];

        $scope.address = {};
        $scope.tickets = {};
        $scope.messages = [];
        $scope.tasks = [];
        $scope.courses = [];
        $scope.hasTickets = false;
        $scope.hasAddress = false;
        $scope.today = new Date();
        $scope.loading = false;
        $scope.hasPhysicalBooksToShip = false;
        $scope.hasValidAddress = false;
        $scope.dateShipped = null;
        $scope.shipment = null;
        $scope.trackingNumber = null;
        $scope.addressClicked = 0;
        $scope.attempts = 0;

        $scope.initialize = function () {
            $scope.today = new Date();
            $scope.GetTerms().then(function() {
                    var term = $scope.selectedTerm.termToUse;
                    $scope.changeTerm(term);
                },
                function() {
                });
        };

        $scope.changeTerm = function(term) {
            // Term was changed, update what we have on the screen            
            $scope.loading = true;
            $scope.GetViewModel(term);
            $scope.GetCurrentAddress(term);
            $scope.GetTickets(term);
        };
        
        $scope.GetCurrentAddress = function (term) {

            url = $scope.baseUrl + "api/home/address/current/"+term;
            $http.get(url).then(function (response) {
                // this callback will be called asynchronously
                // when the response is available
                var data = response.data;
                $scope.address = data;
                if (data !== null) {
                    $scope.hasAddress = true;
                }
            },function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                $scope.address = {};
            });
        };
        $scope.GetAddress = function () {
            $scope.hasAddress = undefined;
            $scope.addressClicked = 1;
            $scope.attempts = 0;
            url = $scope.baseUrl + "api/home/address/enter";
            $http.get(url).then(function(response) {
                var data = response.data;
                $scope.address = data;
                $scope.address.shipName = $scope.address.name;
                $scope.shippingInstructions();
            }, function() {
                $scope.shipInstructions = 'There was a problem processing your address.';
            });
        };

        $scope.cancelAddress = function() {
            $scope.addressClicked = 0;
            $scope.attempts = 0;
        };

        $scope.submitAddress = function () {
            url = $scope.baseUrl + "api/home/address/validate?term=" + $scope.selectedTerm.termToUse;
            $http.post(url, $scope.address).then(function(response) {
                var data = response.data;
                if (data.isValid) {
                    $scope.hasAddress = true;
                }
            });
            $scope.attempts += 1;
        };

        $scope.postCurrentAddress = function(address) {
            url = $scope.baseUrl + "api";
            $scope.selectedTerm = "";
        };

        $scope.GetTickets = function (term) {
            url = $scope.baseUrl +  "api/home/tickets/new/"+term;
            $http.get(url).then(function (response) {
                var data = response.data;
                // this callback will be called asynchronously
                // when the response is available

                $scope.tickets = data;
                if (data !== null) {
                    $scope.hasTickets = true;
                }
            },function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                $scope.hasTickets = {};
            });
        };

        $scope.GetViewModel = function(term) {
            courseFactory.getViewmodel(term).then(function(response) {
                    var data = response.data;
                    $scope.courses = data.enrolledCourses;
                    $scope.content = data.availableDigitalContent;
                    $scope.tasks = data.tasks;
                    $scope.messages = data.messages;
                    $scope.addressClicked = false;
                    $scope.hasPhysicalBooksToShip = data.hasPhysicalBooksToShip;
                    $scope.hasValidAddress = data.hasValidAddress;
                    $scope.hasAddress = $scope.hasValidAddress;
                    $scope.dateShipped = data.dateShipped;
                    $scope.shipment = data.shipment;
                    $scope.trackingNumber = data.TrackingNumber;
                    $scope.loading = false;
                    $scope.shippingInstructions();
                },
                function(data) {
                    $scope.loading = false;
                });
        };

        $scope.shippingInstructions = function() {            
            if (!$scope.courses.length) {
                $scope.shipInstructions = "You do not have any enrolled courses.";
            }

            if ($scope.courses.length && !$scope.hasPhysicalBooksToShip) {
                $scope.shipInstructions =  "All of your current courses are digital or in iLearn and do not require a physical book. You do not need to complete an address at this time.";
            }

            if ($scope.hasPhysicalBooksToShip) {
                if ($scope.selectedTerm.shipDate <= $scope.today && !$scope.hasValidAddress) {
                    $scope.shipInstructions =  'One or more of your courses require a physical book and we are unable to ship this material because the ship date has passed.You will need to withraw from any courses that have physical books and only select courses with digital materials.';
                }
                if (!($scope.selectedTerm.shipDate <= $scope.today) && !$scope.hasValidAddress) {
                    $scope.shipInstructions =  'One or more of your courses requires a physical book be shipped to you. You must submit a valid shipping address.';
                }
                if (!($scope.selectedTerm.shipDate <= $scope.today) && $scope.hasValidAddress) {
                    $scope.shipInstructions =  'We have received your address for shipping. You do not need to call us to verify. Your materials will ship to this address.';
                }
            }
        };

        $scope.GetTerms = function ()
        {
            return courseFactory.getStudentTerms()
                .then(function (response) {
                    // 1. Get dates
                    // 2. Figure out primary date
                    // 3. If primary and active are same - skip active
                    // 4. Get Active
                    // 5. Get Next dates, if primary is a next, skip it
                        var data = response.data;
                        var primaryTerm = $scope.getPrimaryTerm(data);
                        $scope.terms.push(primaryTerm);
                        $scope.selectedTerm = primaryTerm;

                        var needActive = true;
                        $scope.availableTerms = data;
                        // Split out our terms object
                        if ($scope.availableTerms.activeSemester && data.activeSemester !== primaryTerm)
                        {
                            var suffix = $scope.availableTerms.activeSemester.termToUse.substr(-1);
                            if (suffix === "4")
                            {
                                // Move to the fall semester by default
                                $scope.selectedTerm = data.next;
                                $scope.terms.push(data.next);
                                $scope.terms.push(data.activeSemester);
                            }
                            else
                            {
                                $scope.terms.push(data.activeSemester);
                                $scope.terms.push(data.next);
                            }
                            needActive = false; // don't set it again                            
                        }
                        else if(data.next && primaryTerm !== data.next)
                        {
                            $scope.terms.push(data.next);                            
                        }
                },
                function() {
                    $scope.availableTerms = {};
                });
        };

        $scope.getPrimaryTerm = function(data)
        {
            if (data.activeSemester) {
                var date = new Date(data.activeSemester.firstDayOfClass);
                date.setDate(date.getDate()+(9 * 7));
                if (date > new Date()) {
                    return data.activeSemester;
                }
            }
            // active is already well underway
            if (data.next)
            {
                return data.next;
            }
            else {
                return data.activeSemester;
            }
        }

        $scope.GetMessages = function (term) {
            url = $scope.baseUrl + "api/home/messages/new";
            $http.post(url).then(function (response) {
                var data = response.data;
                // this callback will be called asynchronously
                // when the response is available
                $scope.messages = data;
            }, function (response) {
                var data = response.data;
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                $scope.messages = [];
            });
        };

        $scope.markAsRead = function (messageId) {
            var term = selectedTerm.termToUse;
            url = $scope.baseUrl + "api/home/messages/read/"+term+"/" + messageId;
            $http.post(url).then(function (response) {
                var data = response.data;
                var index = $scope.tasks.indexOf(messageId);
                $scope.tasks.splice(index, 1);
            }, function (data, status, headers, config) {

            });
        };

        $scope.GetTasks = function (term) {
            url = $scope.baseUrl + "api/home/tasks/new/"+term;
            $http.post(url).then(function (response) {
                var data = response.data;
                // this callback will be called asynchronously
                // when the response is available
                $scope.tasks = data;
            },function (data, status, headers, config) {
                // called asynchronously if an error occurs
                // or server returns response with an error status.
                $scope.tasks = [];
            });
        };

        $scope.markAsRead = function (messageId) {
            url = $scope.baseUrl + "api/home/tasks/completed/" + messageId;
            $http.post(url).then(function (response) {
                var index = $scope.tasks.indexOf(messageId);
                $scope.tasks.splice(index, 1);
            },function (data, status, headers, config) {

            });
        };
    }]);