module Honey
  class Client
    include HTTParty
    format :xml
    base_uri 'https://www.honeysplace.com/ws/'

    def initialize(account = '', token = '')
      login(account, token)
    end

    def submit_order(order)
      post build_order(order)
    end

    def order_status(reference_number)
      post build_order_status(reference_number)
    end

    def stock_check(*skus)
      skus = skus.first if skus.first.is_a? Array
      skus.each_slice(25).map do |sku_group|
        data = post(build_stock_check(*sku_group)).stock['item']
        stock_hash(data)
      end.reduce({}, :merge)
    end

    def data_feed(code, format)
      DataFeed.new(code, format)
    end

    def build_order(order)
      request(order: order)
    end

    def build_order_status(reference_number)
      request(orderstatus: reference_number)
    end

    def build_stock_check(*skus)
      request(stockcheck: skus.map { |sku| { sku: sku } })
    end

    private

    def stock_hash(data)
      # API returns single element not wrapped in array
      data = [data] unless data.is_a?(Array)

      data.map do |datum|
        [datum['sku'], datum['qty'].to_i]
      end.to_h
    end

    def post(xml)
      Honey::Response.new(self.class.post('', { query: { xmldata: xml }}))
    end

    def login(account, token)
      @builder = Honey::Builder.new(account, token)
    end

    def request(object)
      @builder.build(object)
    end
  end
end
