# Module used for jslog_formatter
module JSLoggerUtils
  class JSErrorLogger

    @browser_log_include = ['samplemediaplayer.js', 'worker.js']
    @client_log_include = ['execute async script', 'execute script']
    @remove_text = 'org.openqa.selenium.remote.server.DriverServlet org.openqa.selenium.remote.server.rest.ResultConfig.handle'
    @browser_logs, @client_logs = [], []

    class << self

      # Save logs for the scenario and used when scenario is failed
      # Also clear the previous logs
      def get_logs
        @browser_logs = Capybara.current_session.driver.browser.manage.logs.get('browser') if self.available_log_types.include? 'browser'
        @client_logs = Capybara.current_session.driver.browser.manage.logs.get('client') if self.available_log_types.include? 'client'
      end

      # Filters the log based on text that needs to included using filter_logs method
      # @return [Array] Failure logs
      def filtered_logs
        filtered_browser_logs = filter_logs('BROWSER', @browser_logs, @browser_log_include)
        filtered_client_logs = filter_logs('CLIENT', @client_logs, @client_log_include)
        all_logs = (filtered_browser_logs + filtered_client_logs).sort
        return all_logs
      end

      # @param log_type [String] Can be 'BROWSER' or 'CLIENT' Used to identify log
      # @param logs [Array] Raw logs from selenium
      # @param include_text [Array] Array of desired text to look into logs
      # @param exclude_text [Array] Array of text which needs to be excluded while filtering
      # @return [Array] Filtered logs based on INclude and Exclude text for log messages
      def filter_logs(log_type, logs, include_text, exclude_text=nil)
        filtered_logs = []
        logs.each do |log|
          # Flag to include or not include the log.
          # Flag `-1` means remove the log
          # Flag `0` means include the log
          flag = -1
          log_msg = log.message
          # Gets logs which have the desired include_text
          include_text.each { |inc| flag = 0 if log_msg.include? inc }
          # add the selected log if flag value is `0`
          filtered_logs << ["#{log.timestamp} - [#{log_type}] - #{log.message.gsub(@remove_text, '')}"] if flag == 0
        end
        return filtered_logs
      end

      # Creates array of available log types for the browsers
      def available_log_types
        return @available_types ||= Capybara.current_session.driver.browser.manage.logs.available_types.map { |type| type.to_s }
      end

      # @return [Boolean] Return true if JSLoggerUtils is to be added
      def supported?
        return ENV['TEST_SUITE'] == 'player_core' && ENV['BROWSER'] == 'chrome'
      end
    end
  end
end
