/*jshint eqnull:true, browser:true */
/* global ich */
(function (Twitch, $) {
  var NewBanner = function (options, el) {
    // jscs:disable requireCamelCaseOrUpperCaseIdentifiers
    // Check to see whether this banner has been enabled
    if (!SiteOptions[options.optionName]) {
      return;
    }

    var attachBannerTemplate = function (bannerName, dismissKeys, templateOptions, elem) {
      var $banner = ich[bannerName](templateOptions);
      elem.prepend($banner);
      if (!!dismissKeys) {
        $banner.find('.js-dismiss-banner#' + bannerName).on('click', function () {
          $banner.hide();
          Twitch.storage.set(templateOptions.dismissKey, true);
        });
      }
    };

    var addBanner = function (login, payoutEntity, isPayable, attribute, bannerName, states, requiredStates, dismissKeys, shouldCheckPayable, elem) {
      var bannerOptions = {},
          dismissKey = "",
          shouldShowBanner = false,
          inBadState = false,
          inSuccessState = false,
          inPendingState = false,
          attributeState = payoutEntity[attribute];

      if (states.actionRequired) {
        inBadState = states.actionRequired.indexOf(attributeState) > -1;
      }
      if (states.success) {
        inSuccessState = states.success.indexOf(attributeState) > -1;
      }
      if (states.pending) {
        inPendingState = states.pending.indexOf(attributeState) > -1;
      }

      if (inSuccessState) {
        dismissKey = dismissKeys.success;
        shouldShowBanner = !Twitch.storage.get(dismissKey);
        bannerOptions.showDismissButton = true;
        bannerOptions.showActionButton = true;
      } else if (inPendingState) {
        dismissKey = dismissKeys.pending;
        shouldShowBanner = !Twitch.storage.get(dismissKey);
        bannerOptions.showDismissButton = true;
      } else if (inBadState) {
        bannerOptions.actionRequired = inBadState;
        bannerOptions.showActionButton = true;
        shouldShowBanner = true;
      }

      if (!shouldShowBanner && shouldCheckPayable && !isPayable.payable) {
        shouldShowBanner = true;
      }

      if (shouldShowBanner && requiredStates) {
        $.each(requiredStates, function(i, s) {
          if ($.inArray(payoutEntity[s.attribute], s.states) < 0) {
            shouldShowBanner = false;
          }
        });
      }

      if (shouldShowBanner) {
        Twitch.storage.del(dismissKey);
        bannerOptions[payoutEntity.partner_state] = true;
        bannerOptions[attributeState] = true;
        bannerOptions.login = login;
        bannerOptions.dismissKey = dismissKey;
        attachBannerTemplate(bannerName, dismissKeys, bannerOptions, elem);
      }
    };

    Twitch.user().then(function (userData) {
      data = {
        login: userData.login,
        isStaff: userData.is_staff
      }
      return RSVP.hash(data);
    }).then(function (data) {
      results = {
        payoutEntity: Twitch.api.get('/api/channels/' + data.login + '/payout_entity'),
        login: data.login,
        isStaff: data.isStaff
      }
      if (options.activeProductOnly) {
        results.product = Twitch.api.get('/api/channels/' + data.login + '/product');
      }
      return RSVP.hash(results);
    }).then(function (results) {
      if (results.payoutEntity && options.shouldCheckPayable && !results.isStaff) {
        results.isPayable = Twitch.api.get('/api/payouts/is_payee_payable');
      }
      return RSVP.hash(results);
    }).then(function (results) {
      var entity = results.payoutEntity;
      if (!entity.partner_state || entity.caller_id !== entity.owner_id) {
        return;
      }

      if (options.activeProductOnly) {
        if (!results.product) {
          return;
        }
      }

      if (results.isStaff) {
        return;
      }

      addBanner(results.login,
        entity,
        results.isPayable,
        options.attribute,
        options.bannerName,
        options.states,
        options.requiredStates,
        options.dismissKeys,
        options.shouldCheckPayable,
        el);
    }, function(e) {
      if (e && e.status === 401) {
        /* Silence known error: unauthenticated */
        return;
      }
      throw e;
    });
    // jscs:enable requireCamelCaseOrUpperCaseIdentifiers
  }

  var badTaxStates = ['start', 'failed', 'missing', 'no_form', 'requires_substantiation'],
      pendingTaxStates = ['pending', 'substantiation_pending'],
      successTaxStates = ['success'];

  var banners = {
    newBanner: NewBanner,
    serviceTaxOptions: {
      bannerName: "service_tax_banner",
      optionName: "tax_notifications_enabled",
      attribute: "service_tax_state",
      states: {
        actionRequired: badTaxStates,
        pending: pendingTaxStates,
        success: successTaxStates
      },
      dismissKeys: {
        pending: "Twitch.tax.pendingServiceBannerDismissed",
        success: "Twitch.tax.successServiceBannerDismissed"
      }
    },
    royaltyTaxOptions: {
      bannerName: "royalty_tax_banner",
      optionName: "tax_notifications_enabled",
      attribute: "royalty_tax_state",
      states: {
        actionRequired: badTaxStates
      },
      requiredStates: [
        {
          attribute: "individual_partner",
          states: [true]
        }
      ],
      shouldCheckPayable: true
    },
    paymentAmendmentOptions: {
      bannerName: "payment_amendment_banner",
      optionName: "payment_amendment_notifications_enabled",
      activeProductOnly: true,
      attribute: "net_payment_amendment",
      states: {
        actionRequired: ["unsigned"]
      }
    },
    internationalPaymentsOptions: {
      bannerName: "international_payments_banner",
      optionName: "international_payments_notifications_enabled",
      activeProductOnly: true,
      attribute: "accept_international_payments",
      states: {
        actionRequired: [false]
      },
      requiredStates: [
        {
          attribute: "net_payment_amendment",
          states: ["accepted_by_default", "signed"]
        }
      ]
    }
  };

  Twitch.mixin({
    banners: banners
  });
})(Twitch, jQuery);
