class Message_Parser

    REPLACE_QUERY = 'REPLACE INTO `linecount` VALUES '
    @@linecounts = {}
    @@queries_queue = []

    singleton_class.alias_method :parse_message_extension_linecount_later, :parse
	def self.parse(message)
        parse_message_extension_linecount_later(message)
        split_message = message.split('|')
        room = split_message[0] == '' ? 'lobby' : split_message[0][1..-1].chomp
		case split_message[1]
        when 'J', 'j', 'join'
            user = split_message[2]
            user_id = Tools.to_id(user)
            @@queries_queue.push("REPLACE INTO `seen` VALUES (CURDATE(), '#{user_id}');")
		when 'chat', 'c'
			room = Rooms.add(room)
			user = Users.add(split_message[2])
			self.add_linecount(room, user)
		when 'c:'
			room = Rooms.add(room)
			user = Users.add(split_message[3])
			self.add_linecount(room, user)
        end
    end

    def self.add_linecount(room, user)
        @@linecounts[room.id] = {} if !@@linecounts[room.id]
        @@linecounts[room.id][user.id] = 0 if !@@linecounts[room.id][user.id]
        @@linecounts[room.id][user.id] += 1
    end

    def self.update_linecount
        query = REPLACE_QUERY
        @@linecounts.dup.each {|room, value|
            next if room.empty?
            @@linecounts[room].dup.each {|user, value| 
                query << "(CURDATE(), `lines` + 1,'#{room}','#{user}'), "
            }
        }
        @@linecounts = {}
        # trim ending comma, add semicolon
        Tools.query("#{query[0..-3]};") if query != REPLACE_QUERY
        Scheduler.schedule(100, Proc.new {Message_Parser.update_linecount})
    end
    def self.push_sql_queue
        if !@@queries_queue.empty?
            Tools.query(@@queries_queue[0])
            @@queries_queue.shift
        end
        Scheduler.schedule(60, Proc.new {Message_Parser.push_sql_queue})
    end
end

Scheduler.schedule(400, Proc.new {Message_Parser.update_linecount})
Scheduler.schedule(60, Proc.new {Message_Parser.push_sql_queue})