"use strict";

App.config(function ($routeProvider) {

    $routeProvider.when(BASE_URL + "/media/mobile_gallery_music_album/index/value_id/:value_id/album_id/:album_id", {
        controller: 'MediaGalleryMusicAlbumController',
        templateUrl: BASE_URL + "/media/mobile_gallery_music_album/template",
        code: "media-gallery-music-page media-gallery-music-album"
    });

}).controller('MediaGalleryMusicAlbumController', function ($scope, $routeParams, $location, Url, MediaMusicAlbum, MediaMusicTrack, MediaMusicTracksLoaderService, MediaMusicPlayerService) {

    $scope.$watch("isOnline", function (isOnline) {
        $scope.has_connection = isOnline;
        $scope.loadContent();
    });

    $scope.is_loading = true;

    $scope.value_id = $routeParams.value_id;
    MediaMusicAlbum.value_id = $routeParams.value_id;
    MediaMusicTrack.value_id = $routeParams.value_id;

    $scope.loadContent = function () {

        MediaMusicAlbum.find($routeParams.album_id).success(function (data) {
            $scope.album = data.album;
            
            MediaMusicTrack.findByAlbum($routeParams.album_id).success(function (data) {

                $scope.album.tracks = data.tracks;

            }).finally(function () {
                $scope.is_loading = false;
            });

        }).error(function () {
            $scope.is_loading = false;
        });
    };

    $scope.play = function (trackIndex) {

        if ($scope.is_loading) return;
        
        MediaMusicPlayerService.init(document);
        
        var tracksLoader = MediaMusicTracksLoaderService._buildTracksLoaderForSingleAlbum($scope.album, $scope.album.tracks);
        
        MediaMusicPlayerService.playTracks(tracksLoader, trackIndex);
    };
    
});