module Bits
  class TransactionsController < Bits::BaseController
      def index
        authorize User
        @msg = params[:user_id]
        
        if params[:user_id].present?
          @user = User.find(params[:user_id])
        end

        @twitch_user = Twitch::User.find(@user.id)

        cursor = ""
        if params[:cursor].present?
          cursor = params[:cursor]
        end

        response = @user.get_transactions(cursor)
        unless response.success?
          flash[:error] = 'Failed to get user transactions'
          return
        end

        @cursor = response.body['cursor']
        @events = response.body['events']

        ids = @events.map { |e| e['channel_id']}.uniq

        twitch_users = Twitch::User.all({
          :where => {
              :id => ids
          }
        })

        id_to_login = {}
        twitch_users.each { |twitch_user|
          id_to_login[twitch_user.id.to_s] = twitch_user.login
        }

        @events.each { |event|
          event['channel_login'] = id_to_login[event['channel_id']]
          event['type'] = get_type(event)
        }
      end

      def get_type(event)
        unless event['admin_id'].empty?
          if event['total'].positive?
            return 'Admin Give Bits'
          else
            return 'Admin Remove Bits'
          end
        end

        if event['channel_id'] == @user.id
          if event['total'].positive?
            return 'Acquire Bits'
          else
            return 'Remove Bits'
          end
        end

        unless event['extension_id'].empty?
          return 'Use Bits In Extension'
        end

        'Use Bits'
      end
    end
end
