class History
	include Mongoid::Document

	field :me, type: String
	field :_with, type: String

    embeds_many :messages, cascade_callbacks: true
    accepts_nested_attributes_for :messages

    index({ me: 1, _with: 1 }, { unique: false })

    def self.find_me_with(me, with)
        where(me: me, _with: with).limit(1).first
    end

    def self.save_message(me, from, message, chat_with, chat_id = nil)
        _with = chat_id.blank? ? chat_with : chat_id
        history = find_me_with(me, _with)

        history = History.new(me: me, _with: _with) if history.nil?

        record = Message.new(message: message, from: from)
        history.messages << record

        history.save
        record.id
    end

    def self.page_history(me, with, page, per_page)
        # Aggregation DSL: WIP (https://github.com/mongoid/origin/pull/59)
        History.collection.aggregate([
            {'$match' => {me: me, _with: with}},
            {'$limit' => 1},
            {'$project' => {:messages => 1}},
            {'$unwind' => '$messages'},
            {'$sort' => {'messages.created_at' => -1}},
            {'$skip' => page * per_page},
            {'$limit' => per_page},
            {'$sort' => {'messages.created_at' => 1}},
            {'$project' => {message: '$messages.message', from: '$messages.from', created_at: '$messages.created_at', id: '$messages._id'}}
        ])
    end
end