(function (context, $) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.RedeemCompleteScreen = function (app) {

    var EVENTS = context.JK.EVENTS;
    var logger = context.JK.logger;
    var rest = context.JK.Rest();
    var jamTrackUtils = context.JK.JamTrackUtils;
    var checkoutUtils = context.JK.CheckoutUtilsInstance;

    var $screen = null;
    var $navigation = null;
    var $templatePurchasedJamTrack = null;
    var $thanksPanel = null;
    var $jamTrackInBrowser = null;
    var $jamTrackInClient = null;
    var $purchasedJamTrack = null;
    var $purchasedJamTrackHeader = null;
    var $purchasedJamTracks = null;
    var userDetail = null;
    var step = null;
    var downloadJamTracks = [];
    var purchasedJamTracks = null;
    var purchasedJamTrackIterator = 0;
    var $backBtn = null;
    var $downloadApplicationLink = null;
    var $noPurchasesPrompt = null;
    var shoppingCartItem = null;
    var $startUsingJtPopup = null;


    function beforeShow() {
      context.JK.Tracking.redeemCompleteTrack()

      $noPurchasesPrompt.addClass('hidden')
      $purchasedJamTracks.empty()
      $thanksPanel.addClass("hidden")
      $purchasedJamTrackHeader.attr('status', 'in-progress')
      $jamTrackInBrowser.addClass('hidden')
      $jamTrackInClient.addClass('hidden')
    }

    function afterShow(data) {



      // if there is no current user, but it apperas we have a login cookie, just refresh
      if(!context.JK.currentUserId && $.cookie('remember_token')) {
        window.location.reload();
      }
      else {
        redeemJamTrack()
      }

      //prepThanks()
    }

    function handleShoppingCartResponse(carts) {

      if(!checkoutUtils.hasOnlyFreeItemsInShoppingCart(carts)) {
        // the user has multiple items in their  shopping cart.  They shouldn't be here.
        logger.error("invalid access of redeemComplete page")
        window.location = '/client#/jamtrack/search'
      }
      else {

        rest.placeOrder()
          .done(function(purchaseResponse) {
            rest.updateUser()

            checkoutUtils.setLastPurchase(purchaseResponse)
            jamTrackUtils.checkShoppingCart()

            prepThanks();
          })
          .fail(app.ajaxError)
      }
    }

    function redeemJamTrack() {
      rest.getShoppingCarts()
        .done(handleShoppingCartResponse)
        .fail(app.ajaxError);

    }

    function beforeHide() {
      if(downloadJamTracks) {
        context._.each(downloadJamTracks, function(downloadJamTrack) {
          downloadJamTrack.destroy();
          downloadJamTrack.root.remove();
        })

        downloadJamTracks = [];
      }
      purchasedJamTracks = null;
      purchasedJamTrackIterator = 0;
    }

    function prepThanks() {
      showThanks();
    }

    function showThanks(purchaseResponse) {


      var purchaseResponse = checkoutUtils.getLastPurchase();

      if(!purchaseResponse || purchaseResponse.length == 0) {
        // user got to this page with no context
        logger.debug("no purchases found; nothing to show")
        $noPurchasesPrompt.removeClass('hidden')
      }
      else {
        if(gon.isNativeClient) {
          $jamTrackInClient.removeClass('hidden')
        }
        else {
          $jamTrackInBrowser.removeClass('hidden');
        }
        $thanksPanel.removeClass('hidden')
        handleJamTracksPurchased(purchaseResponse.jam_tracks)
      }
    }

    function handleJamTracksPurchased(jamTracks) {
      // were any JamTracks purchased?
      var jamTracksPurchased = jamTracks && jamTracks.length > 0;
      if(jamTracksPurchased) {
        if(gon.isNativeClient) {
          $jamTrackInClient.removeClass('hidden')
          context.JK.GA.virtualPageView('/redeemInClient');
          startDownloadJamTracks(jamTracks)
        }
        else {
          $jamTrackInBrowser.removeClass('hidden');

          app.user().done(function(user) {
            // relative to 1 day ago (24 * 60 * 60 * 1000)
            if(new Date(user.created_at).getTime() < new Date().getTime() - 86400000) {
              logger.debug("existing user recorded")
              context.JK.GA.virtualPageView('/redeemInBrowserExistingUser');
            }
            else {
              logger.debug("new user recorded")
              context.JK.GA.virtualPageView('/redeemInBrowserNewUser');
            }
          })



          app.user().done(function(user) {
            if(!user.first_downloaded_client_at) {
              $downloadApplicationLink.removeClass('hidden')
            }
          })
        }


        console.log("jamtracks", jamTracks)
        $startUsingJtPopup.attr('href', '/popups/jamtrack-player/' + jamTracks[0].id)
        $startUsingJtPopup.find('.download-jamkazam').html('Click Here to Start Using <b>' + jamTracks[0].name + '</b>')
        context.JK.popExternalLinks($startUsingJtPopup.parent())
      }
    }

    function startDownloadJamTracks(jamTracks) {
      // there can be multiple purchased JamTracks, so we cycle through them

      purchasedJamTracks = jamTracks;

      // populate list of jamtracks purchased, that we will iterate through graphically
      context._.each(jamTracks, function(jamTrack) {
        var downloadJamTrack = new context.JK.DownloadJamTrack(app, jamTrack, 'small');
        var $purchasedJamTrack = $(context._.template(
          $templatePurchasedJamTrack.html(),
          jamTrack,
          {variable: 'data'}
        ));

        $purchasedJamTracks.append($purchasedJamTrack)

        // show it on the page
        $purchasedJamTrack.append(downloadJamTrack.root)

        downloadJamTracks.push(downloadJamTrack)
      })

      iteratePurchasedJamTracks();
    }

    function iteratePurchasedJamTracks() {
      if(purchasedJamTrackIterator < purchasedJamTracks.length ) {
        var downloadJamTrack = downloadJamTracks[purchasedJamTrackIterator++];

        // make sure the 'purchasing JamTrack' section can be seen
        $purchasedJamTrack.removeClass('hidden');

        // the widget indicates when it gets to any transition; we can hide it once it reaches completion
        $(downloadJamTrack).on(EVENTS.JAMTRACK_DOWNLOADER_STATE_CHANGED, function(e, data) {

          if(data.state == downloadJamTrack.states.synchronized) {
            logger.debug("jamtrack " + downloadJamTrack.jamTrack.name + " synchronized;")
            //downloadJamTrack.root.remove();
            downloadJamTrack.destroy();

            // go to the next JamTrack
            iteratePurchasedJamTracks()
          }
        })

        logger.debug("jamtrack " + downloadJamTrack.jamTrack.name + " downloader initializing")

        // kick off the download JamTrack process
        downloadJamTrack.init()

        // XXX style-test code
        // downloadJamTrack.transitionError("package-error", "The server failed to create your package.")

      }
      else {
        logger.debug("done iterating over purchased JamTracks")
        $purchasedJamTrackHeader.attr('status', 'done')
      }
    }

    function events() {
      $backBtn.on('click', function(e) {
        e.preventDefault();

        context.location = '/client#/jamtrack/search'
      })
    }

    function initialize() {
      var screenBindings = {
        'beforeShow': beforeShow,
        'afterShow': afterShow,
        'beforeHide': beforeHide
      };
      app.bindScreen('redeemComplete', screenBindings);

      $screen                     = $("#redeemCompleteScreen");
      $templatePurchasedJamTrack  = $('#template-purchased-jam-track');
      $thanksPanel                = $screen.find(".thanks-panel");
      $jamTrackInBrowser          = $screen.find(".jam-tracks-in-browser");
      $jamTrackInClient           = $screen.find(".jam-tracks-in-client");
      $purchasedJamTrack          = $thanksPanel.find(".thanks-detail.purchased-jam-track");
      $purchasedJamTrackHeader    = $purchasedJamTrack.find(".purchased-jam-track-header");
      $purchasedJamTracks         = $purchasedJamTrack.find(".purchased-list")
      $backBtn                    = $screen.find('.back');
      $downloadApplicationLink    = $screen.find('.download-jamkazam-wrapper');
      $noPurchasesPrompt          = $screen.find('.no-purchases-prompt')
      $startUsingJtPopup          = $screen.find('.jt-popup')

      if ($screen.length == 0) throw "$screen must be specified";

      events();
    }

    this.initialize = initialize;

    return this;
  }
})
(window, jQuery);