require 'csv'

module AWS

  class Products

    attr_accessor :driver
    attr_accessor :wait
    attr_accessor :current_wait_element
    attr_accessor :product_info

    DEFAULT_URL = "https://aws.amazon.com/products/?nc2=h_ql_prod"

    def initialize
    end

    def create_driver_and_navigate_to(url=DEFAULT_URL)
      @driver = Selenium::WebDriver.for :chrome
      @wait = Selenium::WebDriver::Wait.new(:timeout => 60)

      driver.navigate.to url if url

      @current_wait_element = wait.until {
        input = driver.find_elements(:tag_name, 'a').find{|e| e['data-panel'] == 'm-nav-panel-products'}
        input if input and input['data-panel'] == 'm-nav-panel-products'
      }

      driver
    end

    def product_category_elements
      driver.find_elements(:class_name, 'm-nav-panel-content')
    end

    def product_elements(category_element)
      category_element.find_elements(:class_name, 'm-nav-panel-link')
    end

    def product_info(product_element)
      info = {}

      a = product_element.find_element(:tag_name, 'a')
      info['link'] = a['href'].strip
      info['name'] = a['text'].strip

      begin
        span = a.find_element(:tag_name, 'span')
        info['description'] = span.attribute('innerHTML')

        # now clean up the product name
        info['name'] = info['name'].gsub(info['description'], '').strip
      rescue
        # no span
      end

      info
    end

    def all_product_info
      unless @product_info
        @product_info = {}

        product_category_elements.each do |pce|
          infos = product_elements(pce).map{|pe| product_info(pe)}
          category = infos[0]['name']
          @product_info[category] = infos
        end
      end

      @product_info
    end

    def product_info_as_csv
      header = %w{ Category Name Description Link}

      lines = []
      lines << header
      all_product_info.keys.each do |category|
        all_product_info[category].each do |product|
          lines << [
            category,
            product['name'],
            product['description'],
            product['link']
          ]
        end
      end

      lines.map(&:to_csv)
    end

    def product_info_as_yml
      all_product_info.to_yaml
    end

  end

end
