package net.cobem.grizzly.communication.events.messenger;

import net.cobem.grizzly.Grizzly;
import net.cobem.grizzly.communication.EventRequest;
import net.cobem.grizzly.communication.GameEvent;
import net.cobem.grizzly.communication.composers.messenger.SendFriendRequestComposer;
import net.cobem.grizzly.habbohotel.sessions.Session;
import net.cobem.grizzly.storage.DatabaseResult;

import java.util.Arrays;

public class RequestFriendshipEvent implements GameEvent {

    @Override
    public void compose(Session Session, EventRequest Request) {
        String Name = Request.readString();

        if (Session.getHabbo().getUsername().equals(Name)) {
            return;
        }

        Session Reciever = Grizzly.getHabboHotel().getSessions().getByName(Name);

        if (Reciever == null) {
            DatabaseResult User = Grizzly.getStorage().preparedQuery("SELECT id FROM users WHERE username = ?", Arrays.asList(Name));

            int UserID = User.getInt();

            if (UserID == 0) {
                return;
            }

            DatabaseResult RequestCheck = Grizzly.getStorage().preparedQuery("SELECT id FROM messenger_requests WHERE from_id = ? AND to_id = ?", Arrays.asList(String.valueOf(Session.getHabbo().getID()), String.valueOf(UserID)));

            if (RequestCheck.getInt() != 0) {
                return;
            }

            Grizzly.getStorage().preparedQuery("INSERT INTO messenger_requests (from_id, to_id) VALUES (?, ?)", Arrays.asList(String.valueOf(Session.getHabbo().getID()), String.valueOf(UserID)));
        } else {
            DatabaseResult RequestCheck = Grizzly.getStorage().preparedQuery("SELECT id FROM messenger_requests WHERE from_id = ? AND to_id = ?", Arrays.asList(String.valueOf(Session.getHabbo().getID()), String.valueOf(Reciever.getHabbo().getID())));

            if (RequestCheck.rowCount() != 0) {
                return;
            }

            Reciever.getHabbo().getMessenger().GrabRequests().put(Session.getHabbo().getID(), Session.getHabbo());

            Reciever.sendResponse(SendFriendRequestComposer.compose(Session.getHabbo().getID(), Session.getHabbo().getUsername(), Session.getHabbo().getLook()));

            Grizzly.getStorage().execute("INSERT INTO messenger_requests (from_id, to_id) VALUES ( " +
                    "'" + Session.getHabbo().getID() + "', " +
                    "'" + Reciever.getHabbo().getID() + "')");
        }
    }

}
