<?php
namespace OCA\Bookmarks\Middleware;


use OCA\Bookmarks\Exception\ChildrenOrderValidationError;
use OCA\Bookmarks\Exception\UnsupportedOperation;
use OCP\AppFramework\Db\DoesNotExistException;
use OCP\AppFramework\Db\MultipleObjectsReturnedException;
use OCP\AppFramework\Http;
use OCP\AppFramework\Http\JSONResponse;
use OCP\AppFramework\Middleware;

class ExceptionMiddleware extends Middleware {
	public function afterException($controller, $methodName, \Exception $exception) {
		if (strpos(get_class($controller), 'OCA\\Bookmarks\\Controller\\') !== 0) {
			throw $exception;
		}

		if ($exception instanceof MultipleObjectsReturnedException) {
			return new Http\DataResponse(['status' => 'error', 'data' => 'Multiple parent folders found'], Http::STATUS_INTERNAL_SERVER_ERROR);
		}
		if ($exception instanceof UnsupportedOperation) {
			return new Http\DataResponse(['status' => 'error', 'data' => 'Unsupported operation'], Http::STATUS_BAD_REQUEST);
		}
		if ($exception instanceof DoesNotExistException) {
			return new Http\DataResponse(['status' => 'error', 'data' => 'Could not find item'], Http::STATUS_BAD_REQUEST);
		}
		if ($exception instanceof ChildrenOrderValidationError) {
			return new JSONResponse(['status' => 'error', 'data' => 'invalid children order: ' . $exception->getMessage()], Http::STATUS_BAD_REQUEST);
		}
	}
}
