# parse the main scans.io/json file
require 'json'

module ScansIoTools
  class ScansIoIndexParser
    attr_accessor :json_index, :parsed_data

    def initialize(json_index)
      @json_index = json_index
      @parsed_data = self.parse_json
    end

    def parse_json
      JSON.parse(json_index)
    end

    def studies
      # should be an array of 30 studies
      # .keys
      # ["status", "files", "long_desc", "name", "tags", "short_desc", "contact", "authors", "organization", "uniqid"]
      parsed_data['studies'].map do |st|
        st
      end
    end

    def study_names
      studies.map do |st|
        st['name']
      end
    end

    def study(study_name)
      # pass in a study name to parse the array of all 30 studies
      # .keys
      # ["status", "files", "long_desc", "name", "tags", "study", "short_desc", "updated_at", "contact", "authors", "organization", "created_at", "uniqid"]
       studies.select do |study|
        study['name'] == "#{study_name}"
      end.first
    end

    def file_info(study_name)
      study(study_name)['files']
    end

    def has_filenames?(study_name)
      file_lookup = file_info(study_name)
      # check if the lookup includes a file in the results 
      if file_lookup == [] 
        return false
      else
        return true
      end
    end

    def filenames_for(study_name)
      file_info(study_name).select do |file|
        file['name']
      end.map do |file|
        file['name']
      end
    end

    def fingerprints_for(study_name)
      file_info(study_name).map do |file|
        file['fingerprint']
      end
    end

    def file_urls_for(study_name)
      file_info(study_name).map do |file|
        file['name']
      end
    end
    
    def size_for(study_name)
      if file_info(study_name).count >= 2
        file_info(study_name).select {|name| name['size']}
      else
        file_info(study_name).first['size']
      end
    end
  end
end