(function(context,$) {

    "use strict";
    context.JK = context.JK || {};
    context.JK.LocalRecordingsDialog = function(app) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var showing = false;
        var perPage = 10;
        var openingRecording = false;

        function tbody() {
            return $('#local-recordings-dialog table.local-recordings tbody');
        }

        function emptyList() {
            tbody().empty();
        }

        function resetPagination() {
            $('#local-recordings-dialog .paginator').remove();
        }


        function beforeShow() {
            openingRecording = false;
            emptyList();
            resetPagination();
            showing = true;
            getRecordings(0)
                .done(function(data, textStatus, jqXHR) {
                    // initialize pagination
                    var $paginator = context.JK.Paginator.create(parseInt(jqXHR.getResponseHeader('total-entries')), perPage, 0, onPageSelected)
                    $('#local-recordings-dialog .paginator-holder').append($paginator);
                });
        }

        function afterHide() {
            showing = false;
        }


        function onPageSelected(targetPage) {
            return getRecordings(targetPage);
        }

        function getRecordings(page) {
            return rest.getClaimedRecordings({page:page + 1, per_page:10})
                .done(function(claimedRecordings) {

                    emptyList();

                    var $tbody = tbody();

                    var recordings = $.map(claimedRecordings, function(val, i) { return val.recording; });
                    var localResults = context.jamClient.GetLocalRecordingState({recordings: recordings});

                    if(localResults['error']) {
                        app.notify({
                            title : "Get Recording State Failure",
                            text : localResults['error'],
                            "icon_url": "/assets/content/icon_alert_big.png"
                        });
                        app.layout.closeDialog('localRecordings');
                        return;
                    }

                  console.log("GetLocalRecordingState", localResults)

                    $.each(claimedRecordings, function(index, claimedRecording) {

                        var options = {
                            recordingId: claimedRecording.recording.id,
                            //date: context.JK.formatDate(claimedRecording.recording.created_at),
                            //time: context.JK.formatTime(claimedRecording.recording.created_at),
                            timeago: $.timeago(claimedRecording.recording.created_at),
                            name: claimedRecording.name,
                            aggregate_state: localResults.recordings[index]['aggregate_state'],
                            duration: context.JK.prettyPrintSeconds(claimedRecording.recording.duration)
                        };

                        var tr = $(context._.template($('#template-claimed-recording-row').html(), options, { variable: 'data' }));

                        tr.data('server-model', claimedRecording);
                        $tbody.append(tr);
                    });
                })
                .fail(function(jqXHR, textStatus, errorMessage) {
                    app.ajaxError(jqXHR, textStatus, errorMessage);
                });
        }

        function registerStaticEvents() {
           $('#local-recordings-dialog table.local-recordings tbody').on('click', 'tr', function(e) {

               if(openingRecording) {
                 // prevent double-click spam
                 logger.debug("localRecordingDialog: ignoring duplicate open attempt")
                 return false;
               }

               var localState = $(this).attr('data-local-state');

               if(localState == 'MISSING') {
                   app.notify({
                           title : "Can't Open Recording",
                           text : "The recording is missing all tracks",
                           "icon_url": "/assets/content/icon_alert_big.png"
                   });
               }
               else if(localState == 'PARTIALLY_MISSING') {
                   app.notify({
                       title : "Can't Open Recording",
                       text : "The recording is missing some tracks",
                       "icon_url": "/assets/content/icon_alert_big.png"
                   });
               }
               else
               {
                   var claimedRecording = $(this).data('server-model');

                   openingRecording = true;

                   // tell the server we are about to start a recording
                   rest.startPlayClaimedRecording({id: context.SessionStore.id(), claimed_recording_id: claimedRecording.id})
                       .done(function(response) {

                           // update session info
                           context.SessionActions.updateSession.trigger(response);

                           var recordingId = $(this).attr('data-recording-id');
                           var openRecordingResult = context.jamClient.OpenRecording(claimedRecording.recording);

                           logger.debug("OpenRecording response: %o", openRecordingResult);

                           if(openRecordingResult.error) {
                               app.notify({
                                   "title": "Can't Open Recording",
                                   "text": openRecordingResult.error,
                                   "icon_url": "/assets/content/icon_alert_big.png"
                               });

                               rest.stopPlayClaimedRecording({id: context.SessionStore.id(), claimed_recording_id: claimedRecording.id})
                                   .fail(function(jqXHR) {
                                       app.notify({
                                           "title": "Couldn't Stop Recording Playback",
                                           "text": "Couldn't inform the server to stop playback. msg=" + jqXHR.responseText,
                                           "icon_url": "/assets/content/icon_alert_big.png"
                                       });
                                   })
                           }
                           else {
                               app.layout.closeDialog('localRecordings');
                               $(this).triggerHandler('openedSession', {});
                           }
                       })
                       .fail(function(jqXHR) {
                           app.notifyServerError(jqXHR, "Unable to Open Recording For Playback");

                       })
                       .always(function() {
                         openingRecording = false;
                       })


               }
               return false;
           })
        }

        function initialize(){
            var dialogBindings = {
                'beforeShow' : beforeShow,
                'afterHide': afterHide
            };

            app.bindDialog('localRecordings', dialogBindings);

            registerStaticEvents();
        };


        this.initialize = initialize;
        this.isShowing = function isShowing() { return showing; }
    }

  return this;
})(window,jQuery);