<?php

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

    /**
    * Process incoming request for the /round 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 /round/{id} or /round/{id}/user endpoint
                if ($uriParams) {
                    $lenUriParams = count($uriParams);
                    // Check if it is the /round/{id}/user endpoint
                    if (($lenUriParams == 2) && ($uriParams[1]=='user')) {
                        return $this->getUsersInRound($uriParams[0]);
                    }
                    // Nope, it is the /round/{id} endpoint
                    return $this->getRound($uriParams[0]);
                }
                // If there is no uriParams, it is the /round endpoint
                return $this->getAllRounds();
                break;
            case 'POST':
                $body = $this->request->getData();
                return $this->newRound($body);
                break;
        }
        $message = json_encode(["message" => "unsupported parameters or method in round"]);
        return Response::errorResponse($message);
    }

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

    /**
    * (GET) Get a specific round in Round table based 
    *
    * @return    Response
    */
    protected function getRound($id)
    {
        $rounds = Round::getRow($id);
        $response = Response::okResponse(json_encode($rounds, JSON_PRETTY_PRINT));
        return $response;
    }

    /**
    * (GET) Get Users of the round $id
    *
    * @return    Response
    */
    protected function getUsersInRound($id)
    {
        $rounds = Round::getUsersInRound($id);
        $response = Response::okResponse(json_encode($rounds, JSON_PRETTY_PRINT));
        return $response;
    }

    /**
    * (POST) Add a new round in Round table
    *
    * @param    array    $array    array containing ID_GAME, PREVAILING_WIND ,SEED
    * @return    Response
    */
    protected function newRound($array)
    {
        Round::createRound($array);
        $message = json_encode(["message" => 'Round succesfully created!']);
        $response = Response::createdResponse($message);
        return $response;
    }


}