(function (context, $) {

  "use strict";
  context.JK = context.JK || {};
  context.JK.CheckoutCompleteScreen = 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 $giftCardPurchased = 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;


    function beforeShow() {

    }


    function afterShow(data) {
      prepThanks()
    }


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

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

    function prepThanks() {
      $noPurchasesPrompt.addClass('hidden')
      $purchasedJamTracks.empty()
      $thanksPanel.addClass("hidden")
      $purchasedJamTrackHeader.attr('status', 'in-progress')
      step = 3;
      renderNavigation();
      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 {
        $thanksPanel.removeClass('hidden')
        handleJamTracksPurchased(purchaseResponse.jam_tracks)
        handleGiftCardsPurchased(purchaseResponse.gift_cards)
      }
    }


    function handleGiftCardsPurchased(gift_cards) {
      // were any GiftCards purchased?
      if(gift_cards && gift_cards.length > 0) {
         $giftCardPurchased.removeClass('hidden')
      }
    }
    function handleJamTracksPurchased(jamTracks) {
      // were any JamTracks purchased?
      var jamTracksPurchased = jamTracks && jamTracks.length > 0;
      if(jamTracksPurchased) {
        if(gon.isNativeClient) {
          startDownloadJamTracks(jamTracks)
        }
        else {
          $jamTrackInBrowser.removeClass('hidden');
          app.user().done(function(user) {
            if(!user.first_downloaded_client_at) {
              $downloadApplicationLink.removeClass('hidden')
            }
          })
        }
      }
    }

    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 clearOrderPage() {
      $orderContent.empty();
    }

    function renderNavigation() {
      $navigation.html("");
      var navigationHtml = $(
        context._.template(
          $('#template-checkout-navigation').html(),
          {current: step, purchases_disable_class: gon.global.purchases_enabled ? 'hidden' : ''},
          {variable: 'data'}
        )
      );

      $navigation.append(navigationHtml);
    }

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

        context.location = '/client#/checkoutOrder'
      })
    }

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

      $screen                     = $("#checkoutCompleteScreen");
      $navigation                 = $screen.find(".checkout-navigation-bar");
      $templatePurchasedJamTrack  = $('#template-purchased-jam-track');
      $thanksPanel                = $screen.find(".thanks-panel");
      $jamTrackInBrowser          = $screen.find(".thanks-detail.jam-tracks-in-browser");
      $giftCardPurchased          = $screen.find('.thanks-detail.gift-card')
      $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')

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

      events();
    }

    this.initialize = initialize;

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