require 'yaml'

module Devops
  class Messages

    @@messages = {}
    class << self
      def init
        lang = lang_key
        file = File.expand_path("../../messages/#{lang}.yml", __FILE__)
        merge(file)
      rescue => e
        puts "Can not load messages from '#{file}'"
        exit -6
      end

      def merge file
        lang = lang_key
        messages = read_file(file)[lang]
        raise "It is undefined main key '#{lang}' in file '#{file}'" if messages.nil?
        @@messages.deep_merge!(messages)
      end

      def translate key, params={}
        msg = @@messages
        key.split(".").each do |msgk|
          msg = msg[msgk]
          raise "Invalid message key '#{key}'" if msg.nil?
        end
        raise "Invalid message value with key '#{key}', it must be a string" unless msg.is_a?(String)
        unless msg.nil?
          params.each do |k, v|
            msg = msg.gsub("%{#{k}}", v.to_s)
          end
        end
        msg
      end

      alias_method :t, :translate

      private
      def read_file file_path
        YAML.load_file(file_path)
      end

      def lang_key
        locale = DevopsConfig.config && DevopsConfig.config['messages.lang']
        locale || "en"
      end
    end

  end
end
