require "chamber"

module PushyDaemon
  class ConfigMissingParameter    < StandardError; end
  class ConfigOtherError          < StandardError; end
  class ConfigParseError          < StandardError; end

  class Conf
    extend Chamber

    class << self
      attr_reader :name
      attr_reader :spec
      attr_reader :files
      attr_reader :version
      attr_reader :env
      attr_reader :host
    end

    def self.prepare args = {}
      # Context parameters
      fail PushyDaemon::ConfigMissingParameter, "missing root" unless (@root = args[:root])
      fail PushyDaemon::ConfigMissingParameter, "missing env"  unless (@env = args[:env])

      # Gemspec parameter
      gemspec_path = "#{args[:root]}/#{args[:gemspec]}.gemspec"
      fail PushyDaemon::ConfigMissingParameter, "missing gemspec" unless args[:gemspec]
      fail PushyDaemon::ConfigMissingParameter, "gemspec file not found: #{gemspec_path}" unless File.exist?(gemspec_path)

      # Init host if missing
      @host ||= `hostname`.to_s.chomp.split(".").first

      # Load Gemspec
      @spec     = Gem::Specification::load gemspec_path
      @name     = @spec.name
      @version  = @spec.version
      fail PushyDaemon::ConfigMissingParameter, "missing name" unless @name

      # Init Chamber (defaults, etc, cmdline)
      @files = ["#{args[:root]}/defaults.yml"]
      @files << File.expand_path("/etc/#{@name}.yml")
      @files << args[:config].to_s if args[:config]

      # Load configuration files
      load files: @files, namespaces: { environment: @env }

      # Override some values
      self[:log] ||= {}
      if args[:logfile]
        self[:log][:file] = args[:logfile].to_s
      end

      # Init New Relic
      prepare_newrelic self[:newrelic]

      # Try to access any key to force parsing of the files
      self[:dummy]

    rescue Psych::SyntaxError => e
      fail PushyDaemon::ConfigParseError, e.message
    rescue StandardError => e
      fail PushyDaemon::ConfigOtherError, "#{e.message} \n #{e.backtrace.to_yaml}"
    end

    def self.dump
      self.to_hash.to_yaml
    end

    def Conf.newrelic_enabled?
      !!self[:newrelic]
    end

  protected

    def self.prepare_newrelic section
      unless section.is_a?(Hash)
        # puts "prepare_newrelic: no config found"
        ENV["NEWRELIC_AGENT_ENABLED"] = "false"
        return
      end
      # puts "prepare_newrelic: #{section.inspect}"

      # Enable GC profiler
      GC::Profiler.enable

      # Enable module
      ENV["NEWRELIC_AGENT_ENABLED"] = "true"
      ENV["NEW_RELIC_MONITOR_MODE"] = "true"

      # License
      ENV["NEW_RELIC_LICENSE_KEY"] = section[:licence].to_s

      # Appname
      platform = section[:platform] || self.host
      section[:app_name] ||= "#{self.name}-#{platform}-#{self.env}"
      ENV["NEW_RELIC_APP_NAME"] = section[:app_name].to_s

      # Logfile
      ENV["NEW_RELIC_LOG"] = section[:logfile].to_s
    end


  end
end