<?php
// TODO : ID partie, Nom de la partie, nombres de joueurs déjà connectés

class GameController extends Controller
{
    public function __construct($name, $request)
    {
        parent::__construct($name, $request);
    }

    /**
    * Process incoming request for the /game endpoint
    *
    * @return    Response
    */
    public function processRequest()
    {
        $httpMethod=$this->request->getHttpMethod();
        $uriParams=$this->request->getUriParams();

        switch ($httpMethod) {
            case 'GET':
                // If there is a uriParams, it is the /game/{id} endpoint
                if ($uriParams) {
                    if ($uriParams[0]=='public'){
                        return $this->getAllPublicGames($uriParams[0]);
                    }
                    return $this->getGame($uriParams[0]);
                }
                // Else, it is the /game endpoint
                return $this->getAllGames();
                break;
            case 'POST':
                $body = $this->request->getData();
                return $this->newGame($body);
                break;
        }
        $message = json_encode(["message" => "unsupported parameters or method in game"]);
        return Response::errorResponse($message);
    }

    /**
    * (GET) Get all games in Game table
    *
    * @return    Response
    */
    protected function getAllGames()
    {
        $games = Game::getList();
        $response = Response::okResponse(json_encode($games, JSON_PRETTY_PRINT));
        return $response;
    }

    /**
    * (GET) Get a specific game in Game table based on id
    *
    * @return    Response
    */
    protected function getGame($id)
    {
        $games = Game::getRow($id);
        $response = Response::okResponse(json_encode($games, JSON_PRETTY_PRINT));
        return $response;
    }

        /**
    * (GET) Get all games in Game table
    *
    * @return    Response
    */
    protected function getAllPublicGames()
    {
        $games = Game::getListPublic();
        $response = Response::okResponse(json_encode($games, JSON_PRETTY_PRINT));
        return $response;
    }

    /**
    * (POST) Add a new game in Game table
    *
    * @param    array    $array    array containing PRIVATE
    * @return    Response
    */
    protected function newGame($array)
    {
        Game::createGame($array);
        $message = json_encode(["message" => 'Game succesfully created!']);
        $response = Response::createdResponse($message);
        return $response;
    }
}