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

import net.cobem.grizzly.Grizzly;
import net.cobem.grizzly.communication.EventRequest;
import net.cobem.grizzly.communication.GameEvent;
import net.cobem.grizzly.communication.composers.navigation.SendUserRoomsComposer;
import net.cobem.grizzly.habbohotel.rooms.Room;
import net.cobem.grizzly.habbohotel.sessions.Session;
import net.cobem.grizzly.storage.DatabaseResult;
import net.cobem.grizzly.utils.UserInputFilter;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class SearchRoomEvent implements GameEvent {

    @Override
    public void compose(Session Session, EventRequest Request) {
        Map<Integer, Room> Return = new HashMap<Integer, Room>();

        String Search = Request.readString();

        String Query = Search.split(":")[0];
        String Value = null;

        if (Search.contains(":")) {
            Value = UserInputFilter.filterString(Search.split(":")[1], false);
        }

        if (Query != null && Value != null) {
            switch (Query) {
                case "owner":
                    DatabaseResult GrabOwner = Grizzly.getStorage().preparedQuery("SELECT id FROM server_users WHERE username = ?", Arrays.asList(Value));

                    int Owner = GrabOwner.getInt();

                    DatabaseResult GrabRooms = Grizzly.getStorage().preparedQuery("SELECT * FROM server_rooms WHERE owner = ?", Arrays.asList(String.valueOf(Owner)));

                    try {
                        ResultSet Results = GrabRooms.getTable();

                        while (Results.next()) {
                            Return.put(Results.getInt("id"), new Room(Results));
                        }
                    } catch (SQLException e) {
                        //
                    }
                    break;

                case "user_count":

                    break;
            }
        } else {
            DatabaseResult GrabRooms = Grizzly.getStorage().preparedQuery("SELECT * FROM server_rooms WHERE name LIKE %?%", Arrays.asList(Search));

            try {
                ResultSet Results = GrabRooms.getTable();

                while (Results.next()) {
                    Return.put(Results.getInt("id"), new Room(Results));
                }
            } catch (SQLException e) {
                //
            }
        }

        Session.sendResponse(SendUserRoomsComposer.compose(Return));
    }

}
