aboutsummaryrefslogtreecommitdiff
path: root/lib/osugiru/messages.rb
blob: 4af19b6954996a7141ffe171071460b08e94b643 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# frozen_string_literal: true

require 'pry'
module Osugiru
  class Messages
    AND_CONJUCTION = :and
    OR_CONJUCTION = :or
    DEFAULT_CONJUCTION = AND_CONJUCTION

    Token = Struct.new(:conjuction, :field, :value, :messages) do
      def to_query
        conjuction_to_use = messages.next_token_id > 1 ? conjuction : ''
        return "#{conjuction_to_use} (#{value})" if field == :direct

        "#{conjuction_to_use} (#{field}:#{value})"
      end
    end

    TokenGroup = Struct.new(:conjuction, :tokens, :messages) do
      def initialize(*)
        super
      end

      def to_query
        tokens.flat_map(&:to_query).join(' ').to_s
      end

      def push_token(field, value)
        if value.is_a? String
          tokens.push(Token.new(conjuction, field, value, messages))
        elsif value.is_a? Array
          group = TokenGroup.new(OR_CONJUCTION, [], messages)
          value.each do |val|
            group.push_token(field, val)
          end
          tokens.push group

        end
      end

      def next_token_id
        @token_count += 1
      end
    end

    attr_accessor :query, :current_conjuction, :token_count
    attr_reader :db

    def initialize(db:)
      @db = db
      @query = []
      @current_conjuction = AND_CONJUCTION
      @token_count = 0
    end

    def or
      @current_conjuction = OR_CONJUCTION
      self
    end

    def and
      @current_conjuction = AND_CONJUCTION
      self
    end

    def filter(params)
      case params
      when String
        add_filter_from_string(params)
      when Hash
        add_filter_from_hash(params)
      end

      self
    end

    def each
      db.search_messages(query_string).each do |msg|
        yield(Message.new(msg: msg))
      end
    end

    def add_filter_from_string(string)
      @query << Token.new(current_conjuction, :direct, string, self)
    end

    def add_filter_from_hash(hash)
      group = TokenGroup.new(current_conjuction, [], self)
      hash.each do |key, value|
        group.push_token(key, value)
      end
      @query << group
    end

    def query_string
      query.map(&:to_query).join(' ')
    end

    def next_token_id
      @token_count += 1
    end
  end
end