module XCPerfect
  # Parser is used by `Formatter`s to extract information from the
  # JSON file generated by xccov
  class Parser
    KEY_TARGETS = 'targets'.freeze
    KEY_EXECUTABLE_LINES = 'executableLines'.freeze
    KEY_COVERED_LINES = 'coveredLines'.freeze

    attr_accessor :json

    def initialize(json)
      @json = json
    end

    def valid?
      expected_project_keys = %w[coveredLines lineCoverage targets executableLines name]
      expected_target_keys = %w[coveredLines lineCoverage name files executableLines buildProductPath]

      return false unless (expected_project_keys - @json.keys).length.zero?

      all_targets.each do |target|
        return false unless (expected_target_keys - target.keys).length.zero?
      end
    end

    def extract_targets(desirables)
      if desirables.length.zero?
        all_targets
      else
        all_targets.select do |target_info|
          pure_name = target_info['name'].split('.')
          pure_name.pop(1)
          pure_name = pure_name.join('.')
          desirables.include?(pure_name)
        end
      end
    end

    def all_targets
      @json[KEY_TARGETS]
    end

    def extract_coverage_info(target)
      [
        target['name'],
        covered_line_num(target),
        total_line_num(target),
        coverage_percentage(target)
      ]
    end

    def coverage_percentage(target)
      target['lineCoverage'].round(2)
    end

    def covered_line_num(target)
      target['coveredLines']
    end

    def total_line_num(target)
      target['executableLines']
    end
  end
end
