'use strict';

rockBandsApp.controller('EditAlbumController',
    function EditAlbumController($scope, $location, $templateCache, $routeParams, rockBandsData) {
        var baseUrl = '/albums',
            albumUrl = '/home';

        if ($routeParams.name) {
            albumUrl = '/album/' + $routeParams.name;

            rockBandsData
                .getAlbumByName($routeParams.name)
                .then(function (data) {
                    $scope.$apply(function () {
                        if (!data) {
                            $location.path(baseUrl);
                            return;
                        }

                        $scope.album = data;
                    });
                })
        }

        // Used in select box
        applyBandsDataToScope();

        $scope.updateAlbum = updateAlbum;
        $scope.cancelEdit = cancelEdit;

        function applyBandsDataToScope() {
            rockBandsData
                .getAllBands(null, null, true)
                .then(function (data) {
                    $scope.$apply(function () {
                        $scope.bands = data;
                    });
                });
        }

        function updateAlbum(album, newAlbumForm) {
            if (album && newAlbumForm.$valid) {
                if ($routeParams.name) {
                    updateItem(album);
                }
                else {
                    createItem(album);
                }
            }
        }

        function cancelEdit() {
            $location.path(albumUrl);
        }

        function updateItem(album) {
            rockBandsData
                .updateAlbum(album)
                .then(function () {
                    redirectToBandPage(album);
                }, showRestrictedAccessWindow);
        }

        function createItem(album) {
            rockBandsData
                .createAlbum(album)
                .then(function () {
                    redirectToBandPage(album);
                }, showRestrictedAccessWindow);
        }

        function redirectToBandPage(album) {
            $scope.$apply(function () {
                $templateCache.removeAll();
                var albumUrl = '/album/' + album.Src;
                $location.path(albumUrl);
            });
        }

        function showRestrictedAccessWindow() {
            ErrorModalWindow.showRestrictedAccessWindow();
        }
    }
);