require "httparty"
require "json"

module Acouchi
  class Solo
    MENU = 82

    def send_key key
      call_method("sendKey", [{:type => "int", :value => key}])
    end

    def enter_text index, text
      call_method("enterText", [
        {:type => "int",              :value => index},
        {:type => "java.lang.String", :value => text}
      ])
    end

    def clear_edit_text index
      call_method("clearEditText", [{:type => "int", :value => index}])
    end

    def has_text? text, options={}
      options = {
        :scroll          => true,
        :minimum_matches => 0,
        :must_be_visible => true
      }.merge(options)

      call_method("searchText", [
        {:type => "java.lang.String", :value => text},
        {:type => "int", :value => options[:minimum_matches]},
        {:type => "boolean", :value => options[:scroll]},
        {:type => "boolean", :value => options[:must_be_visible]}
      ])
    end

    def buttons
      call_method("getCurrentButtons")
    end

    def has_button? text
      buttons.any? { |b| b["text"] == text }
    end

    def content
      call_method("getCurrentContent")
    end

    def click_text text, options={}
      options = {
        :match => 1,
        :auto_scroll => true
      }.merge(options)

      call_method("clickOnText", [
        {:type => "java.lang.String", :value => text},
        {:type => "int", :value => options[:match]},
        {:type => "boolean", :value => options[:auto_scroll]}
      ])
    end

    def views
      call_method("getViews")
    end

    def click_view id
      call_method("clickOnViewById", [
        {:type => "int", :value => id},
      ])
    end

    def scroll_up
      call_method("scrollUp")
    end

    def scroll_down
      call_method("scrollDown")
    end

    def scroll_up_list index=0
      call_method("scrollUpList", [
        {:type => "int", :value => index}
      ])
    end

    def scroll_down_list index=0
      call_method("scrollDownList", [
        {:type => "int", :value => index}
      ])
    end

    private
      def call_method name, arguments = []
        options = { :body => {:parameters => arguments.to_json} }
        response = HTTParty.post("http://127.0.0.1:7103/execute_method/#{name}", options)
        json = JSON.parse(response.body, :max_nesting => 100)
        if json.empty?
          nil
        else
          json["result"]
        end
      end
  end
end