# Copyright 2021 - Raghu K

# This class is created to parse the log file and perform following functions.
# Validate the input log file - validate_file? which takes input file path as argument.
# Get the view count -  webpage_views & unique_webpage_views.
# Display views count - display_views_count which takes views count and string as arguments.

class FileParser
	attr_accessor :file_path

	# Validate & Initialize the file path 
	def initialize(file_path)
		validate_file?(file_path)
		self.file_path = file_path
	end

	# Function to parse log file
	def parse_input_file
		File.open(file_path) do |file|
			@parsed_lines = file.readlines
		end
		@parsed_lines
	end

	# Function to get view count
	def webpage_views
		views_count(@parsed_lines)
	end

	# Function to get unique view count
	def unique_webpage_views
		views_count(@parsed_lines.uniq)
	end

	# Function to display view count
	def display_views_count(page_views,string)
		puts " #{string} Count: \n -------------------------- \n "
		page_views.each {|k,val| puts k + "page has " + val.to_s + " Visits"}
	end

	private 

	# Function which takes parsed lines as input and returns view page name and count of visit
	# This function returns sorted Hash map based on value
	def views_count(parsed_lines)
		views_count = Hash.new(0)
		parsed_lines.each do |line|
			page_name = line.split[0]
			views_count[page_name] += 1 
		end
		views_count.sort_by { |k,v| -v }.to_h
	end

	# Function which validate the input log file
	def validate_file?(file_path)
		raise "File path: #{file_path} doesn't exist" unless File.exist? file_path
	end
end