"use strict";

let Messages = function () {

    let db;

    let init = function () {
        db = DB.getDB();
        //db.get('chats').remove().write();
    }

    let getMessages = function (chat_id) { console.error("Messages.getMessages()");
        return db.get('chats').filter({'friend':chat_id}).sortBy('id').takeRight(50).value();
    }

    let exists = function (message_id) { //console.warn("Messages.exists()");
        let msg = getMessage(message_id); //console.log(msg);
        return msg ? true:false;
    }

    let add = function (msg) { console.warn("Messages.add()"); console.log(msg);
        let item = {
            "id": msg.id,
            "friend": msg.getFriendId(),
            "sender": msg.sender_id,
            "receiver": msg.receiver_id,
            "message": msg.message,
            "fecha": msg.fecha,
            "delivered": msg.delivered,
            "read": msg.read,
            "type": msg.type
        }

        db.get('chats').push(item).write();
    }
    
    let getMessage = function (message_id) {
        let item = db.get('chats').find({id: message_id}).value();
        if (item) {
            return compose(item);
        }

        return null;
    }

    let getLastMessage = function (chat_id) { console.warn("Messages.getLastMessage()");
        let item = db.get('chats').filter({'friend':chat_id}).sortBy('id').last().value(); console.log(item);
        if (item) {
            return compose(item);
        }

        return null;
    }

    let getLastMessageId = function (chat_id) { console.warn("Messages.getLastMessageId()");
        let last_message_id = 0;

        let message = getLastMessage(chat_id);
        if (message) { console.log(message);
            last_message_id = message.getId();
        }

        return last_message_id;
    }

    let setDelivered = function (chat_id) { console.warn("Messages.setDelivered()");
        db.get('chats').filter({'friend':chat_id, 'delivered':0}).assign({'delivered':1}).write();
    }

    let compose = function (data) {
        return new Message(
            data.id, data.sender, data.receiver, data.message, data.fecha, data.delivered, data.read, data.type
        );
    }

    let composeRaw = function (data) {
        return new Message(
            data.id, data.sender, data.receiver, data.message, data.date, data.delivered, data.read, data.type
        );
    }

    return {
        init: init,
        add: add,
        compose: compose,
        composeRaw: composeRaw,
        getMessages: getMessages,
        getLastMessage: getLastMessage,
        getLastMessageId: getLastMessageId,
        exists: exists,
        setDelivered: setDelivered
    }
}();