# frozen_string_literal: true

# Story Prompt Generator class for User input
class StoryPromptGenerator
  attr_accessor :errors, :answers
  QUESTIONS = ['A Number (Positive Integer Only)', 'Unit of Measurement',
               'A Place', 'An Adjective', 'A Noun'].freeze
  ERRORS = {
    negative_or_no_number: 'Please Enter A Positive Integer',
    wrong_length: 'Invalid Input Length: 1 - 50 characters only',
    multiple_words: 'Multiple Words Are Not Allowed'
  }.freeze

  def initialize
    welcome_message
  end

  def prompt_user
    @answers = []
    QUESTIONS.map do |question|
      puts "Please Enter #{question}"
      answers << gets.chomp
    end
    evaluate_and_print
  end

  private

  def welcome_message
    message = 'You have to enter a number, a unit of measurement, place,
    adjective and a noun to complete a story (Input should not exceed
    50 characters)'
    puts message
  end

  def evaluate_and_print
    if validate_input
      save_input_data
      print_story(*answers)
    else
      print_errors
    end
  end

  def print_errors
    puts 'Input storage halted due to the following errors'
    @errors.uniq.map do |error|
      puts error
    end
    prompt_user
  end

  def validate_input
    @errors = []
    answers.each_with_index do |ans, index|
      if index.zero? && ans.to_i.negative?
        errors << ERRORS[:negative_or_no_number]
      end
      validate_alphabet_input(ans)
    end
    errors.length.zero?
  end

  def validate_alphabet_input(ans)
    errors << ERRORS[:wrong_length] if ans.length > 50 || ans.length.zero?
    errors << ERRORS[:multiple_words] if ans.include?(' ')
  end

  def print_story(num, unit, place, adj, noun)
    print "THE COMPLETE STORY IS:
    One day Anna was walking her #{num} #{unit} commute
    to #{place} and found a #{adj} #{noun} on the ground."
  end

  def save_input_data
    file = File.open('user_input.txt', 'a')
    answers.map do |answer|
      file.write("#{answer}\n")
    end
    file.close
  end
end
