(function(context,$) {

    "use strict";

    context.JK = context.JK || {};
    context.JK.AccountScreen = function(app) {
        var logger = context.JK.logger;
        var rest = context.JK.Rest();
        var userId;
        var user = {};
        var screen = null;
        var gearUtils = context.JK.GearUtilsInstance;

        function beforeShow(data) {
            userId = data.id;
        }

        function afterShow(data) {
            resetForm();
            renderAccount()
        }

        function resetForm() {
            // remove all display errors
            $('#account-content-scroller form .error-text').remove()
            $('#account-content-scroller form .error').removeClass("error")
        }

        function summarizeSession(userDetail) {
          if(userDetail.upcoming_session_count > 0) {
            return 'You are scheduled to play in ' + userDetail.upcoming_session_count + ' sessions'
          }
          else {
            return 'You are not scheduled to play in any sessions'
          }
        }

        function licenseDetail(userDetail) {
          return (userDetail.purchased_jamtracks_count==0) ? "You don't currently own any JamTracks" : 'You currently own a license to use ' + userDetail.purchased_jamtracks_count + " JamTracks"        
        }

        function populateAccount(userDetail) {

            var validProfiles = prettyPrintAudioProfiles(context.JK.getGoodConfigMap());
            var invalidProfiles = prettyPrintAudioProfiles(context.JK.getBadConfigMap());
            var sessionSummary = summarizeSession(userDetail);

            if(gon.global.video_available && gon.global.video_available!="none" ) {
              var webcamName;
              var webcam = null;
              if (context.jamClient.FTUECurrentSelectedVideoDevice) {
                webcam = context.jamClient.FTUECurrentSelectedVideoDevice()
              }

              if (webcam == null || typeof(webcam) == "undefined" || Object.keys(webcam).length == 0) {
                webcamName = "None Configured"
              } else {
                webcamName = _.values(webcam)[0]
              }
            }
            else {
              webcamName = 'video unavailable'
            }

            var $template = $(context._.template($('#template-account-main').html(), {
              email: userDetail.email,
              name: userDetail.name,
              licenseDetail: licenseDetail(userDetail),
              location : userDetail.location,
              session : sessionSummary,
              paymentMethod: "mastercard",
              instruments : prettyPrintInstruments(userDetail.instruments),
              photoUrl : context.JK.resolveAvatarUrl(userDetail.photo_url),
              validProfiles : validProfiles,
              invalidProfiles : invalidProfiles,
              isNativeClient: gon.isNativeClient,
              musician: context.JK.currentUserMusician,
              sales_count: userDetail.sales_count,
              owned_retailer_id: userDetail.owned_retailer_id,
              is_affiliate_partner: userDetail.is_affiliate_partner,
              affiliate_earnings: (userDetail.affiliate_earnings / 100).toFixed(2),
              affiliate_referral_count: userDetail.affiliate_referral_count,
              owns_school: !!userDetail.owned_school_id,
              owns_retailer: !!userDetail.owned_retailer_id,
              is_onboarder: userDetail.is_onboarder,
              webcamName: webcamName
            } , { variable: 'data' }));

            $('#account-content-scroller').html($template);
            
            if(userDetail.upcoming_session_count > 0) {
              $('#account-scheduled-sessions-link').show();
            } else {
              $('#account-scheduled-sessions-link').hide();
            }
            
        }// function 

        function prettyPrintAudioProfiles(profileMap) {
          var profiles = "";
          var delimiter = ", ";
          if (profileMap && profileMap.length > 0) {
            $.each(profileMap, function(index, val) {
              var inputName = val.name;
              if (inputName == gearUtils.JAMKAZAM_VIRTUAL_INPUT) {
                inputName = gearUtils.SYSTEM_DEFAULT_PLAYBACK_ONLY;
              }
              profiles += inputName + delimiter;
            });

            return profiles.substring(0, profiles.length - delimiter.length);
          }
          else {
            return "N/A";
          }
        }

        function prettyPrintInstruments(instruments) {
            if(!instruments || instruments.length == 0) {
                return "no instruments";
            }
            else {
                var pp = "";
                $.each(instruments, function(index, item) {
                    pp += item.description;
                    if(index < instruments.length - 1) {
                        pp += ", ";
                    }
                })
                return pp;
            }
        }

            // events for main screen
        function events() {
            // wire up main panel clicks:
            $('#account-content-scroller').on('click', '#account-scheduled-sessions-link', function(evt) { evt.stopPropagation(); navToScheduledSessions(); return false; } );
            $('#account-content-scroller').on('click', '#account-manage-subscription', function(evt) { evt.stopPropagation(); navToSubscription(); return false; } );
            $('#account-content-scroller').on('click', '#account-my-jamtracks-link', function(evt) { evt.stopPropagation(); navToMyJamTracks(); return false; } );
            
            $('#account-content-scroller').on('click', '#account-edit-identity-link', function(evt) { evt.stopPropagation(); navToEditIdentity(); return false; } );
            $('#account-content-scroller').on('click', '.account-edit-profile-link', function(evt) { evt.stopPropagation(); navToEditProfile(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-subscriptions-link', function(evt) { evt.stopPropagation(); navToEditSubscriptions(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-payments-link', function(evt) { evt.stopPropagation(); navToEditPayments(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-audio-link', function(evt) { evt.stopPropagation(); navToEditAudio(); return false; } );
            $('#account-content-scroller').on('click', '#account-edit-video-link', function(evt) { evt.stopPropagation(); navToEditVideo(); return false; } );
            $('#account-content-scroller').on('avatar_changed', '#profile-avatar', function(evt, newAvatarUrl) { evt.stopPropagation(); updateAvatar(newAvatarUrl); return false; })

            $("#account-content-scroller").on('click', '#account-payment-history-link', function(evt) {evt.stopPropagation(); navToPaymentHistory(); return false; } );
            $("#account-content-scroller").on('click', '#account-affiliate-partner-link', function(evt) {evt.stopPropagation(); navToAffiliates(); return false; } );
            $("#account-content-scroller").on('click', '#account-school-link', function(evt) {evt.stopPropagation(); navToSchool(); return false; } );
            $("#account-content-scroller").on('click', '#account-retailer-link', function(evt) {evt.stopPropagation(); navToRetailer(); return false; } );
            $("#account-content-scroller").on('click', '#account-onboarder-link', function(evt) {evt.stopPropagation(); navToOnboarder(); return false; } );
        }

        function renderAccount() {
          app.user().done(function() {
            rest.getUserDetail()
              .done(populateAccount)
              .error(app.ajaxError)
          })
        }

        function navToScheduledSessions() {
            resetForm();
            window.location = '/client#/account/sessions'
        }

        function navToSubscription() {
            resetForm();
            window.location = '/client#/account/subscription'
        }

        function navToMyJamTracks() {
            resetForm();
            window.location = '/client#/account/jamtracks'   
        }

        function navToEditIdentity() {
            resetForm()
            window.location = '/client#/account/identity'
        }

        function navToEditProfile() {
            resetForm()
            window.ProfileActions.startProfileEdit(null, false)
        }

        function navToEditSubscriptions() {
          window.ProfileActions.startProfileEdit(null, false)
        }

        function navToEditPayments() {

        }

        function navToEditAudio() {
            resetForm()
            window.location = "/client#/account/audio"
        }

        function navToEditVideo() {
            resetForm()
            window.location = "/client#/account/video"
        }

        function navToPaymentHistory() {
          window.location = '/client#/account/paymentHistory'
        }

        function navToAffiliates() {
          resetForm()
          window.location = '/client#/account/affiliatePartner'
        }

        function navToSchool() {
          resetForm()
          window.location = '/client#/account/school'
        }

        function navToRetailer() {
          resetForm()
          window.location = '/client#/account/retailer'
        }

        function navToOnboarder() {
            resetForm()
            window.location = '/client#/account/onboarder'
        }

        // handle update avatar event
        function updateAvatar(avatar_url) {
            var photoUrl = context.JK.resolveAvatarUrl(avatar_url);
            var avatar = $(new Image());
            avatar.attr('src', photoUrl + '?cache_bust=' + new Date().getTime());
            avatar.attr('alt', "Avatar");
            avatar.attr('id', 'profile-avatar');
            $('#profile-avatar').replaceWith(avatar);
        }

        function navToAccount() {
            resetForm();
            renderAccount();
        }

        function initialize() {
            screen = $('#account-content-scroller');
            var screenBindings = {
                'beforeShow': beforeShow,
                'afterShow': afterShow
            };
            app.bindScreen('account', screenBindings);
            events();
        }

        this.initialize = initialize;
        this.beforeShow = beforeShow;
        this.afterShow = afterShow;
        return this;
    };

})(window,jQuery);
