module SchleuderGitlabTicketing
  class Config
    include SchleuderGitlabTicketing::GitlabConfig

    def initialize(config_path='/etc/schleuder/gitlab.yml')
      @config = if File.exists?(config_path)
                  YAML.load_file(config_path)
                else
                  {}
                end
    end

    # returns true if mail was handled
    # returns 'config-error' if list-config is not properly
    # returns nil if list is not configured to handle
    # gitlab plugin
    def process_list(list_name, mail)
      if l = lists[list_name]
        if l.configured?
          l.process(mail)
        else
          'config-error'
        end
      else
        nil
      end
    end

    def lists
      @lists ||= read_lists
    end

    private
    def read_lists
      Hash(@config['lists']).inject({}) do |res,a|
        n,v = a
        v['gitlab'] ||= gitlab
        v['subject_filters'] = Array(v['subject_filters']) + Array(@config['subject_filters'])
        v['sender_filters'] = Array(v['sender_filters']) + Array(@config['sender_filters'])
        res[n] = SchleuderGitlabTicketing::List.new(n,v)
        res
      end
    end
  end
end
