package electrosphere.net.server.protocol;

import org.joml.Vector3d;

import electrosphere.engine.Globals;
import electrosphere.entity.types.creature.CreatureTemplate;
import electrosphere.net.parser.net.message.CharacterMessage;
import electrosphere.net.parser.net.message.PlayerMessage;
import electrosphere.net.server.ServerConnectionHandler;
import electrosphere.net.template.ServerProtocolTemplate;
import electrosphere.server.character.PlayerCharacterCreation;
import electrosphere.server.datacell.Realm;
import electrosphere.util.Utilities;

/**
 * The server protocol for handling character messages
 */
public class CharacterProtocol implements ServerProtocolTemplate<CharacterMessage> {

    @Override
    public CharacterMessage handleAsyncMessage(ServerConnectionHandler connectionHandler, CharacterMessage message) {
        return message;
    }

    @Override
    public void handleSyncMessage(ServerConnectionHandler connectionHandler, CharacterMessage message) {
        switch(message.getMessageSubtype()){
            case REQUESTCHARACTERLIST:
                //TODO
                break;
            case REQUESTCREATECHARACTER:
                CreatureTemplate template = Utilities.deserialize(message.getdata(), CreatureTemplate.class);
                if(template != null){
                    connectionHandler.setCreatureTemplate(Utilities.deserialize(message.getdata(), CreatureTemplate.class));
                    connectionHandler.addMessagetoOutgoingQueue(CharacterMessage.constructResponseCreateCharacterSuccessMessage());
                } else {
                    connectionHandler.addMessagetoOutgoingQueue(CharacterMessage.constructResponseCreateCharacterFailureMessage());
                }
                break;
            case REQUESTSPAWNCHARACTER:
                spawnEntityForClient(connectionHandler);
                break;
            case RESPONSECHARACTERLIST:
            case RESPONSECREATECHARACTERSUCCESS:
            case RESPONSECREATECHARACTERFAILURE:
            case RESPONSESPAWNCHARACTER:
                //silently ignore
                break;
        }
    }

    /**
     * Spawns the player's entity
     * @param connectionHandler The connection handler for the player
     */
    static void spawnEntityForClient(ServerConnectionHandler connectionHandler){
        PlayerCharacterCreation.spawnPlayerCharacter(connectionHandler);
        Realm realm = Globals.playerManager.getPlayerRealm(connectionHandler.getPlayer());
        Vector3d spawnPoint = realm.getSpawnPoint();
        //set client initial discrete position
        connectionHandler.addMessagetoOutgoingQueue(
            PlayerMessage.constructSetInitialDiscretePositionMessage(
                realm.getServerWorldData().convertRealToChunkSpace(spawnPoint.x),
                realm.getServerWorldData().convertRealToChunkSpace(spawnPoint.y),
                realm.getServerWorldData().convertRealToChunkSpace(spawnPoint.z)
            )
        );
    }
    
}
