<?php

declare(strict_types=1);

namespace App\Presenters;

use Nette;
use Exception;

define("COURSE_THEME_BASIC_DATA_TRANSFER", array(
	'ID' => 'ID',
	'nazev' => 'name',
	'popis' => 'description',
	'stav' => 'state',
));

final class CourseThemePresenter extends BasePresenter
{
    public function renderDefault() {}

	public function actionGetAllThemes(): void
	{
		$this->checkUserAccess('instruktor', true);
		$data = $this->courseThemeManager->getAllThemes();
		$json = $this->applyTransfer($data, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON);
		$this->sendJson($json);	
	}

	public function actionCreateTheme(): void
	{
		$this->checkUserAccess('zamestnanec');
		$httpRequest = $this->getHttpRequest();
		$body = $httpRequest->getRawBody();
		$json = json_decode($body);	
		$data = $this->applyTransfer($json, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_DB, DATA_OBJECT);
		$result = $this->courseThemeManager->createTheme($data);

		if(!$result) {
			$this->error('data se nepovedlo ulozit', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
		}

		$json = $this->applyTransfer($result, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON, DATA_OBJECT);
		$this->sendJson($json);	
	}

	public function actionUpdateTheme(): void
	{
		$this->checkUserAccess('zamestnanec');
		$httpRequest = $this->getHttpRequest();
		$body = $httpRequest->getRawBody();
		$json = json_decode($body);	
		$data = $this->applyTransfer($json, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_DB, DATA_OBJECT);
		
		try {
			$result = $this->courseThemeManager->updateTheme($data);
		} catch (Exception $e) {
			$this->error('data se nepovedlo ulozit', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
		}

		$data = $this->courseThemeManager->getThemeById($json->ID);
		$json = $this->applyTransfer($data, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON, DATA_OBJECT);
		$this->sendJson($json);	
	}

	public function actionGetById(): void
	{
        $this->checkUserAccess('instruktor', true);
		$httpRequest = $this->getHttpRequest();
		$id = $httpRequest->getQuery('themeId');
		if($id) {
			$data = $this->courseThemeManager->getThemeById($id);
			if($data != null) {
				$json = $this->applyTransfer($data, COURSE_THEME_BASIC_DATA_TRANSFER, TRANSFER_TO_JSON, DATA_OBJECT);
				$this->sendJson($json);
			}
			$this->error('pozadovana data se nepovedlo nacist', Nette\Http\Response::S500_INTERNAL_SERVER_ERROR);
		} else {
			$this->error('nebyl vlozen parametr id', Nette\Http\Response::S400_BAD_REQUEST);
		}
	}
}
