require_rel '../pages'
require 'phantomjs'

module ERDL
  class URLFetcher
    attr_accessor :fetched_url

    def initialize(opts = {}, browser = nil, route = nil)
      @opts = opts
      @browser_type ||= opts[:browser] ? opts[:browser] : 'chrome'
      case @browser_type
      when 'chrome'
        @browser = browser || Watir::Browser.new(:chrome)
      when 'phantomjs'
        # set path to default $HOME/.phantomjs/VERSION/PLATFORM, installs if not already there
        Selenium::WebDriver::PhantomJS.path = Phantomjs.path
        @browser = browser || Watir::Browser.new(:phantomjs)
      else
        fail "Don't know how to use browser: #{@browser_type}"
      end
      @route = class_from(route) || YouTube::Routes.new(@browser, @opts)
    end

    def url
      self.fetched_url ||= @route.traverse
      return fetched_url
    ensure
      teardown
    end

    def teardown
      @browser.quit if @browser && @browser.respond_to?(:quit)
    end

    private

    # Private: Return module-namespaced Class/Module/CONST from its String representation.
    #
    # Example
    #
    # class_from('YouTube::LoginPage')
    # # => YouTube::LoginPage
    #
    # Raises a RuntimeError if the Class cannot be resolved on Object (perhaps because of incorrect user input?)
    #
    # Returns the Class or Module represented in the String.
    def class_from(str)
      return str unless str.is_a?(String) # return passed-in obj if it's not a String (probably used outside of CLI)
      str.split('::').inject(Object) { |o, c| o.const_get c }
    rescue
      raise "Could not resolve page class from String: #{str}"
    end
  end
end
