require "bundler/setup"
require 'pathname'

require_relative 'fabriq/cli'
require_relative 'fabriq/logging'
require_relative 'fabriq/adapter'
require_relative 'fabriq/config'
require_relative 'fabriq/plugin_port'
require_relative 'fabriq/skype'
require_relative 'fabriq/skype_proxy'

module Fabriq
  extend self
  extend Fabriq::Logging

  def display_env
    ENV["DISPLAY"]
  end

  def display_env=(display)
    ENV["DISPLAY"] = display.to_s
  end

  def root
    Pathname.new(File.expand_path(File.join(File.dirname(__FILE__), "..")))
  end

  def config(&block)
    yield Fabriq::Config
  end

  def boot
    Fabriq::Config.read_config_file
    assert_exported_display_env

    Fabriq::Adapter.load
    Fabriq::Adapter.run { load_environment }
  end

  def argv
    ARGV
  end

  def assert_exported_display_env
    if display_env.nil? || display_env == ""
      if Fabriq::Config.display
        Fabriq.display_env = Fabriq::Config.display
      else
        error "DISPLAY environment variable or config.display not set. This is needed to communicate with the actual Skype client."
        exit(1)
      end
    end

    return true
  end

  def load_environment
    if self.argv.size > 0
      Fabriq::CLI.run(self.argv)
    else
      Fabriq::PluginPort.initialize_plugins
    end
  end
end

# Empty namespace for plugins
module Plugins; end