require 'cloud66_agent/utils/vital_signs'

module Cloud66
  module Utils
    class Config

      # default conf dir
      CONFIG_PATH = "/etc/cloud66/cloud66_agent.yml"

      attr_accessor :api_url,
                    :api_key,
                    :secret_key,
                    :agent_uid,
                    :disabled,
                    :is_aws,
                    :is_gc,
                    :log,
                    :log_level,
                    :disk_warning_percent,
                    :disk_critical_percent

      # load up the config at startup
      def initialize
        load if File.exists?(CONFIG_PATH)

        # set defaults
        @log = @log.nil? ? "/var/log/cloud66_agent.log" : @log == "STDOUT" ? STDOUT : @log
        @log_level ||= 2
        @api_url ||= 'https://api.cloud66.com'
        @disabled ||= false
        @is_aws ||= false
        @is_gc ||= false

        # defaults
        @disk_warning_percent = 80
        @disk_critical_percent = 90
      end

      def is_agent_configured?
        return !@agent_uid.nil? && !@agent_uid.empty?
      end

      def save
        Dir.mkdir(CONFIG_PATH) if !FileTest::directory?(File.dirname(CONFIG_PATH))

        File.open(CONFIG_PATH, 'w+') do |out|
          data = {
              'api_url' => @api_url,
              'api_key' => @api_key,
              'secret_key' => @secret_key,
              'agent_uid' => @agent_uid,
              'disabled' => @disabled,
              'is_aws' => @is_aws,
              'is_gc' => @is_gc,
              'log' => @log == STDOUT ? "STDOUT" : @log,
              'log_level' => @log_level,
              'disk_warning_percent' => @disk_warning_percent,
              'disk_critical_percent' => @disk_critical_percent,
          }
          out.puts to_cust_yaml(data)
        end
      end

      def delete
        File.delete(CONFIG_PATH) if File.exists?(CONFIG_PATH)
      end

      private

      def load
        raise "config not found" unless File.exists?(CONFIG_PATH)
        config = from_cust_yaml(IO.read(CONFIG_PATH))
        @api_url = config['api_url']
        @api_key = config['api_key']
        @secret_key = config['secret_key']
        @agent_uid = config['agent_uid']
        @disabled = config['disabled']
        @is_aws = config['is_aws']
        @is_gc = config['is_gc']
        @log = config['log']
        @log_level = config['log_level']
        @disk_warning_percent = config['disk_warning_percent'].to_i if config['disk_warning_percent']
        @disk_critical_percent = config['disk_critical_percent'].to_i if config['disk_critical_percent']
      rescue
        # we can't load the file
      end

      # temporary measure to handle psych dependency errors
      def to_cust_yaml(hash)
        yaml_output = ''
        hash.each do |key, value|
          if !!value == value || value.is_a?(Integer)
            yaml_output += "#{key}: #{value.to_s}\n"
          else
            yaml_output += "#{key}: \"#{value.to_s}\"\n"
          end
        end
        return yaml_output
      end

      # temporary measure to handle psych dependency errors
      def from_cust_yaml(yaml)
        hash = {}
        yaml.lines.each do |line|
          next if line.nil? || !line.include?(':')
          key = line.split(':', 2)[0].strip
          value = line.split(':', 2)[1].strip
          next if value.empty?

          if value =~ /^(true|false)$/
            value = true if value == 'true'
            value = false if value == 'false'
          elsif value =~ /^[0-9]+$/
            value = value.to_i
          elsif value =~ /^".*"$/
            value = value.gsub(/^"/, '').gsub(/"$/, '')
          end
          hash[key] = value
        end
        return hash
      end

    end
  end
end