(function(context,$) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.ShareDialog = function(app, entityId, entityType) {
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var facebookRest = context.JK.FacebookRest();
    var facebookHelper = null;
    var dialogId = '#share-dialog';
    var userDetail = null;
    var entity = null;
    var remainingCap = 140 - 22 - 1; // 140 tweet max, minus 22 for link size, minus 1 for space
    var clipboard = null;

    function showSpinner() {
        $(dialogId + ' .dialog-inner').hide();
        var spinner = $('<div class="spinner spinner-large"></div>')
        $(dialogId + ' .content-head').after(spinner);
    }

    function hideSpinner() {
        $(dialogId + ' .spinner').remove();
        $(dialogId + ' .dialog-inner').show();
    }


    function checkShareCheckbox(provider, checked) {
        var checkbox = $(dialogId + ' .share-with-' + provider + ' input');

        if(checked) {
            checkbox.attr('checked', 'checked');
        }
        else {
            checkbox.removeAttr('checked');
        }
    }


    function handleRecordingShareWithGoogle(message) {
        var defer = $.Deferred();

        defer.resolve(); // remove when implemented

        return defer;
    }

    function handleShareWithTwitter(message) {
        var defer = $.Deferred();

        rest.tweet({message:  message + ' ' + entity.share_url})
            .done(function() {

                // uncheck facebook, because we don't want the user to re-post to their timeline by accident
                checkShareCheckbox('twitter', false);
                defer.resolve();
            })
            .fail(function(jqXHR) {
                if(jqXHR.status == 422) {
                    // implies twitter token error.

                    var response = JSON.parse(jqXHR.responseText);

                    if(response.errors.token) {
                        app.notify({
                            title : "Failed to Tweet",
                            text : "You need to re-authorize JamKazam to access your Twitter account. Click (sign in) in the Share Dialog.",
                            "icon_url": "/assets/content/icon_alert_big.png"
                        });
                        disableTwitter();
                    }
                    else if(response.errors.twitter) {
                        app.notify({
                            title : "Failed to Tweet",
                            text : "Twitter rejected the tweet because '" + response.errors.twitter[0] + "'",
                            "icon_url": "/assets/content/icon_alert_big.png"
                        });
                    }
                    else {
                        app.notifyServerError(jqXHR, "Unable to Share with Twitter");
                    }
                }
                else {
                    app.notifyServerError(jqXHR, "Unable to Share with Twitter");
                }
                defer.reject();
            });
        return defer;
    }

    function handleRecordingShareWithTwitter(message) {
        return handleShareWithTwitter(message);
    }

    function handleRecordingShareWithFacebook(message) {
        var defer = $.Deferred();

        rest.getShareRecording({ provider:'facebook', claimed_recording: entityId})
            .done(function(data) {
                facebookHelper.promptLogin()
                    .done(function(response) {
                        handleFbStateChange(response);
                        if(response.status == "connected") {
                            facebookRest.post({
                                access_token: response.authResponse.accessToken,
                                message: message,
                                description: data.description,
                                caption: data.caption,
                                name: data.title,
                                picture: data.photo_url,
                                link: data.url
                            }).done(function(response) {
                                checkShareCheckbox('facebook', false);
                                defer.resolve();
                            })
                            .fail(function(response) {
                                app.notify({
                                    title : "Unable to Share with Facebook",
                                    text : "Error: " + response,
                                    "icon_url": "/assets/content/icon_alert_big.png"
                                });
                                defer.reject();
                            })
                        }
                        else {
                            // user doesn't want to auth; this is a form of success
                            defer.resolve();
                        }
                    })
            })
            .fail(function(jqXHR) {
                app.notifyServerError(jqXHR, "Unable to Populate Share Data");
                defer.reject();
            })

        return defer;

    }

    function handleSessionShareWithGoogle(message) {
        var defer = $.Deferred();

        defer.resolve(); // remove when implemented

        return defer;
    }

    function handleSessionShareWithTwitter(message) {
        return handleShareWithTwitter(message);
    }

    function handleSessionShareWithFacebook(message) {
        var defer = $.Deferred();

        rest.getShareSession({ provider:'facebook', music_session: entityId})
            .done(function(data) {
                facebookHelper.promptLogin()
                    .done(function(response) {
                        handleFbStateChange(response);
                        if(response.status == "connected") {
                            facebookRest.post({
                                access_token: response.authResponse.accessToken,
                                message: message,
                                description: data.description,
                                caption: data.caption,
                                name: data.title,
                                picture: data.photo_url,
                                link: data.url
                            })
                            .done(function(response) {
                                checkShareCheckbox('facebook', false);
                                defer.resolve();
                            })
                            .fail(function(response) {
                                    app.notify({
                                        title : "Unable to Share with Facebook",
                                        text : "Error: " + response,
                                        "icon_url": "/assets/content/icon_alert_big.png"
                                    });
                                defer.reject();
                            })
                        }
                        else {
                            // user doesn't want to auth; this is a form of success
                            defer.resolve();
                        }
                    })
            })
            .fail(function(jqXHR) {
                app.notifyServerError(jqXHR, "Unable to Populate Share Data");
                defer.reject();
            })

        return defer;
    }

    function messageTooLongForTwitter(message) {
        return message && message.length > remainingCap;
    }

    function socialShare() {
        var facebookCheckbox = $(dialogId + ' .share-with-facebook input');
        var shareWithFacebook = facebookCheckbox.is(':checked') && !facebookCheckbox.is(':disabled');

        var googleCheckbox = $(dialogId + ' .share-with-google input');
        var shareWithGoogle = googleCheckbox.is(':checked') && !googleCheckbox.is(':disabled');

        var twitterCheckbox = $(dialogId + ' .share-with-twitter input');
        var shareWithTwitter = twitterCheckbox.is(':checked') && !twitterCheckbox.is(':disabled');

        if(!shareWithFacebook && !shareWithGoogle && !shareWithTwitter) {
            $(dialogId + ' .share-options').addClass('error')
            return;
        }
        else {
            $(dialogId + ' .share-options').removeClass('error')
        }


        var message = $(dialogId + ' .share-message').val();
        if(!message) { message = undefined; }

        if(shareWithTwitter && !message) {
            $(dialogId + ' .share-message-holder').addClass('error')
            $(dialogId + ' .share-message-holder .error-msg').text("You must specify a message for Twitter.");
            return;
        }
        else
        {
            $(dialogId + ' .share-message-holder').removeClass('error')
            $(dialogId + ' .share-message-holder .error-msg').text('');
        }

        // validate twitter message length
        if(shareWithTwitter && messageTooLongForTwitter(message)) {
            $(dialogId + ' .share-message-holder').addClass('error')
            $(dialogId + ' .share-message-holder .error-msg').text("Your message must be less than " + (remainingCap + 1) + " characters in length for Twitter (currently " + message.length + ").");
            return;
        }
        else
        {
            $(dialogId + ' .share-message-holder').removeClass('error')
            $(dialogId + ' .share-message-holder .error-msg').text('');
        }

        showSpinner();

        var chain = [];

        if(entityType == 'session') {
            if(shareWithFacebook) {
                chain.push(handleSessionShareWithFacebook(message))
            }
            if(shareWithTwitter) {
                chain.push(handleSessionShareWithTwitter(message))
            }
            if(shareWithGoogle) {
                chain.push(handleSessionShareWithGoogle(message))
            }
        }
        else {
            if(shareWithFacebook) {
                chain.push(handleRecordingShareWithFacebook(message))
            }
            if(shareWithTwitter) {
                chain.push(handleRecordingShareWithTwitter(message))
            }
            if(shareWithGoogle) {
                chain.push(handleRecordingShareWithGoogle(message))
            }
        }

        $.when.apply($, chain)
            .done(function() {
                app.layout.closeDialog('share-dialog');
            })
            .fail(function() {
                logger.error("share failed")
            })
            .always(function() {
                hideSpinner();
            });
    }

    function enableFacebook() {
        $(dialogId + ' .share-with-facebook input').removeAttr('disabled')
        $(dialogId + ' .share-with-facebook a').css('visibility', 'hidden');
    }

    function disableFacebook() {
        $(dialogId + ' .share-with-facebook input').attr('disabled', 'disabled')
        $(dialogId + ' .share-with-facebook a').css('visibility', 'visible');
    }

    function enableTwitter() {
        $(dialogId + ' .share-with-twitter input').removeAttr('disabled')
        $(dialogId + ' .share-with-twitter a').css('visibility', 'hidden');
    }

    function disableTwitter() {
        $(dialogId + ' .share-with-twitter input').attr('disabled', 'disabled')
        $(dialogId + ' .share-with-twitter a').css('visibility', 'visible');
    }

    function handleFbStateChange(response) {

        if (response && response.status == "connected") {
            enableFacebook();
            checkShareCheckbox('facebook', true);
        }
        else{
            disableFacebook();
            checkShareCheckbox('facebook', false);
        }
    }

    function registerEvents(onOff) {
        $(dialogId + ' .dialog-share-button').unbind('click').click(function(e){
            socialShare();
            return false;
        });

        $(dialogId + ' .share-with-facebook a').unbind('click').click(function(e) {
            facebookHelper.promptLogin().done(function(response) {
                handleFbStateChange(response);
            });
            return false;
        });

        $(dialogId + ' .share-with-twitter a').unbind('click').click(function(e) {
            app.layout.queueDialog('share-dialog')
            window.location = '/auth/twitter';
            return false;

        })
    }

    function showDialog() {
        return app.layout.showDialog('share-dialog');
    }

    // function initDialog() {
    //     var sessionText = textMap.SESSION;
    //     var liveSessionText = textMap.LIVE_SESSION;

    //     var fill = entityType === sessionText.toLowerCase() ? "teal-fill" : "orange-fill";

    //     $("#shareType").text(entityType);

    //     $("#divWidgetCodeHeader").addClass(fill);
    //     $("#divWidgetPreviewHeader").addClass(fill);
    //     $("#divWidgetPreview").addClass(entityType);

    //     // SESSION
    //     if (entityType === sessionText.toLowerCase()) {
    //         $("#lblWidgetCodeType").html(sessionText.toLowerCase());
    //         $("#lblWidgetPreviewType").html(sessionText.toLowerCase());
    //         $("#spnWidgetCodeBranding").text(liveSessionText.toLowerCase());
    //         $("#spnWidgetPreviewBranding").text(liveSessionText.toLowerCase());

    //         rest.getSessionHistory(entityId)
    //             .done(function(response) {
    //                $(".link-contents").html(response.share_url);
    //             });
    //     }

    //     // RECORDING
    //     else if (entityType === "recording") {
    //         var recordedText = textMap.RECORDED.toLowerCase();
    //         $("#lblWidgetCodeType").text(textMap.RECORDING);
    //         $("#lblWidgetPreviewType").text(textMap.RECORDING);
    //         $("#spnWidgetCodeBranding").text(recordedText);
    //         $("#spnWidgetPreviewBranding").text(recordedText);

    //         rest.getClaimedRecording(entityId)
    //             .done(function(response) {
    //                 var name, photoUrl;

    //                 if (response.recording.band) {
    //                     name = response.recording.band.name;
    //                     photoUrl = context.JK.resolveBandAvatarUrl(response.recording.band.photo_url);
    //                 }
    //                 else {
    //                     name = response.recording.owner.name;
    //                     photoUrl = context.JK.resolveAvatarUrl(response.recording.owner.photo_url);
    //                 }

    //                 $(".link-contents").html(response.share_url);

    //                 $("#imgWidgetCodeAvatar").attr('src', photoUrl);
    //                 $("#imgWidgetPreviewAvatar").attr('src', photoUrl);

    //                 $("#divWidgetPreviewTitle").html(response.recording.name);

    //                 $("#spnWidgetCodeArtistName").html(name);
    //                 $("#spnWidgetPreviewArtistName").html(name);

    //                 $.each(response.recording.recorded_tracks, function(index, val) {
    //                     $(".widget-members").append('<div class="widget-avatar-small">' + '<img src="' + context.JK.resolveAvatarUrl(val.user.photo_url) + '" alt="" />' + '</div>');
    //                 });
    //             });
    //     }
    // }

    function beforeShow() {
      disableTwitter();
      // no disableFacebook on purpose

      if(entityType == 'recording') {
        rest.getClaimedRecording(entityId)
            .done(function(data) {
                entity = data;
                $(dialogId + ' .link-contents').text(entity.share_url)
            })
            .fail(function(jqXHR) {
                app.notifyServerError(jqXHR, "Unable to Fetch Recording Data");
            })
      }
      else {
        rest.getSession(entityId)
            .done(function(data) {
                entity = data;
                $(dialogId + ' .link-contents').text(entity.share_url)
            })
            .fail(function(jqXHR) {
                app.notifyServerError(jqXHR, "Unable to Fetch Session Data");
            });
      }
      rest.getUserDetail()
          .done(function(data) {
              userDetail = data;
              if(data.auth_twitter) {
                  enableTwitter();
              }
              else {
                  disableTwitter();
              }
          });

      $(dialogId + ' .share-message-holder').removeClass('error')
      $(dialogId + ' .share-message-holder .error-msg').text('');
      $(dialogId + ' .share-options').removeClass('error');
      registerEvents(true);
    }

    function afterShow() {
      $("#shareType").text(entityType);
    }

    function afterHide() {
      hideSpinner();
      registerEvents(false);
    }

    function initialize(_facebookHelper) {
      facebookHelper = _facebookHelper;

      var dialogBindings = {
          'beforeShow' : beforeShow,
          'afterShow' : afterShow,
          'afterHide': afterHide
      };

      app.bindDialog('share-dialog', dialogBindings);

      //initDialog();

      facebookHelper.deferredLoginStatus().done(function(response) { handleFbStateChange(response); });

      if(context.jamClient.IsNativeClient()) {
        $("#btn-share-copy").unbind('click').click(function() {
          context.jamClient.SaveToClipboard($("#link-contents").text());
          return false;
        })
      }
      else {
        clipboard = new Clipboard('#btn-share-copy', {
          text: function(trigger) {
            return $("#link-contents").text();
          }
        })
      }
    }

    this.initialize = initialize;
    this.showDialog = showDialog;
  }

  return this;
})(window,jQuery);
