<?php

class UserController extends Controller {

    public function __construct($name, $request) {
        parent::__construct($name, $request);
    }

    // ==============
    // Actions
    // ==============

    public function processRequest()
    {
         switch ($this->request->getHttpMethod()) {
            case 'GET':
                if ($this->request->getUriParams())
                    return $this->getUser($this->request->getUriParams()[0]);

                return $this->getAllUsers();
                break;
            case 'PUT':
                if ($this->request->getUriParams())
                    return $this->updateUser($this->request->getUriParams()[0],$this->request->getData());
                break;
        }
        return Response::errorResponse("unsupported parameters or method in users");
    }

    protected function getAllUsers()
    {
        $users = User::getList();
        $response = Response::okResponse(json_encode($users));
        //var_dump($json);die;
        // TODO
        return $response;
    }

    protected function getUser($id){
        $user = User::getRow($id);
        $response = Response::okResponse(json_encode($user));
        return $response;
    }
    protected function updateUser($id, $data){
        $sets=[];
        if(isset($data['login'])){
            $sets[] = ['USER_LOGIN',$data['login']];
        }
        if(isset($data['email'])){
            $sets[] = ['USER_EMAIL',$data['email']];
        }
        if(isset($data['role'])){
            $sets[] = ['USER_ROLE',$data['role']];
        }
        if(isset($data['pwd'])){
            $sets[] = ['USER_PWD',$data['pwd']];
        }
        if(isset($data['name'])){
            $sets[] = ['USER_NAME',$data['name']];
        }
        if(isset($data['surname'])){
            $sets[] = ['USER_SURNAME',$data['surname']];
        }
        //$sets = implode(', ', $sets);
        $success = true;
        foreach ($sets as $set ) {
            $success &= User::update($id, $set);
        }
        $response = $success?Response::okResponse("Updated"):Response::errorResponse("failed");
        return $response;
    }
}