module Twitch
  module UserHelper
    # return a link_to that is disabled if user is unauthorized to run :method
    # on :item. same as using link_to except it takes 3 additional keywords.
    #
    # item
    # Service object to check authorization for.
    #
    # method
    # Controller method to check authorization for. Should be a matching pundit
    # policy in ./app/policies
    #
    # unauthorized_text
    # Text to show as tooltip if unauthorized.
    def authorized_link_to(*args, **options)
      unless policy(options[:item]).send(options[:method])
        return render(
          partial: 'unauthorized_link_to',
          locals: {
            unauthorized_text: options.fetch(:unauthorized_text, 'Unauthorized'),
            body: link_to(*args, **options.except(:item, :method), disabled: true)
          }
        )
      end
      link_to(*args, **options.except(:item, :method))
    end

    def twofa_view_state(twofa_status:)
      all = twofa_statuses

      current_state =
        all[:states]
        .map do |k, v|
          if v[twofa_status].nil? && v.respond_to?(:map)
            [
              k,
              v
                .map do |hk, hv|
                  [
                    hk,
                    hv[twofa_status]
                  ]
                end
                .to_h
            ]
          else
            [k, v[twofa_status]]
          end
        end

      current_state
        .to_h
        .merge(all[:defaults]) {|_, v, c| v.merge(c)}
        .map do |k, v|
          if k == :style
            [
              k,
              v
                .map do |hk, hv|
                  [
                    hk.to_s + ':',
                    hv + ';'
                  ]
                end
                .flatten
                .join(' ')
            ]
          else
            [k, v]
          end
        end
        .to_h
    end

    private

    def twofa_statuses
      {
        defaults: {
          data: {'tooltip-position': "bottom"},
          style: {
            'font-size': '20px',
            'line-height': '20px'
          }
        },
        states: {
          data: {
            tooltip: {
              enabled: "2FA is Enabled",
              disabled: "2FA is NOT enabled",
              unknown: "2FA status is unknown\n" + @user.two_factor_errors,
            },
          },
          style: {
            color: {
              enabled: "#5FD453",
              disabled: "#D9534F",
              unknown: "#777",
            },
          },
          class: {
            enabled: "glyphicon glyphicon-ok-sign",
            disabled: "glyphicon glyphicon-remove-circle",
            unknown: "glyphicon glyphicon-question-sign",
          }
        }
      }
    end
  end
end
