require 'open3'
require 'json'

module TrueAutomation
  class Client
    @pid = nil

    def start
      begin
        node_ver = `node -v`
        node_ver = node_ver[1..-1]
        node_versions = node_ver.split('.')
        major_version = node_versions[0]

        if major_version.to_i < 9
          puts "Node version #{node_ver} found. TrueAutomation.IO requires Node 9+ to run."
          exit
        end
      rescue e
        puts 'Node executable can not be found. node version 9+ is required to run TrueAutomation.IO tests.'
        exit
      end

      begin
        trueautomation_version = `trueautomation --version`

        puts "TrueAutomation.IO client #{trueautomation_version.strip}"
      rescue e
        puts 'TrueAutomation.IO npm package is not installed. Run `npm install -g trueautomation` to install it first.'
        exit
      end

      Dir.mkdir('log') unless File.exist?('log')

      logfile = "log/trueautomation-#{Time.now.strftime('%Y%m%dT%H%M%S')}.log"

      @pid = spawn('trueautomation start', out: logfile)

      puts "Started TrueAutomation.IO client with pid #{@pid}"

      @pid
    end

    def stop
      if @pid
        puts "Stopping TrueAutomation.IO Client with pid #{@pid}"
        Process.kill('TERM', @pid)
        @pid = nil
      end
    end

    def wait_until_start
      counter = 0
      loop do
        break if check_connection or counter >= 10
        counter += 1
        sleep 2
      end
    end

    private

    def check_connection
      Socket.tcp('localhost', 9515, connect_timeout: 2) { true } rescue false
    end
  end
end