<?php

namespace SHServ\Controllers;

use \SHServ\Models\Modes;
use \SHServ\Integrations\GAuth\AuthControllerTrait;

class ModesRESTAPIController extends \SHServ\Middleware\Controller {
	use AuthControllerTrait;

	public function list_all() {
		if ($auth = $this -> require_permission('scripts.view')) { return $auth; }

		$modes_model = new Modes();
		$modes_model -> sync_registry_tags();
		$modes = $modes_model -> list_all();

		logging() -> trace('php:Modes', 'Modes list fetched', ['total' => count($modes)]);

		return $this -> utils() -> response_success([
			"modes" => $modes,
			"total" => count($modes)
		]);
	}

	public function active() {
		if ($auth = $this -> require_permission('scripts.view')) { return $auth; }

		$modes_model = new Modes();
		$modes_model -> sync_registry_tags();
		$tags = $modes_model -> active_tags();

		logging() -> trace('php:Modes', 'Active modes fetched', ['tags' => $tags]);

		return $this -> utils() -> response_success([
			"active" => $tags
		]);
	}

	public function enable($tag) {
		if ($auth = $this -> require_permission('scripts.edit')) { return $auth; }

		if(!$this -> validate_tag($tag)) {
			return $this -> utils() -> response_error("invalid_alias", ["tag"]);
		}

		$modes_model = new Modes();
		$modes_model -> sync_registry_tags();
		$result = $modes_model -> enable($tag);

		if(!$result) {
			logging() -> warn('php:Modes', 'Enable mode failed', ['tag' => $tag]);
			return $this -> utils() -> response_error("undefined_error");
		}

		logging() -> info('php:Modes', 'Mode enabled', ['tag' => $tag]);
		return $this -> utils() -> response_success();
	}

	public function disable($tag) {
		if ($auth = $this -> require_permission('scripts.edit')) { return $auth; }

		if(!$this -> validate_tag($tag)) {
			return $this -> utils() -> response_error("invalid_alias", ["tag"]);
		}

		$modes_model = new Modes();
		$modes_model -> sync_registry_tags();
		$result = $modes_model -> disable($tag);

		if(!$result) {
			logging() -> warn('php:Modes', 'Disable mode failed', ['tag' => $tag]);
			return $this -> utils() -> response_error("undefined_error");
		}

		logging() -> info('php:Modes', 'Mode disabled', ['tag' => $tag]);
		return $this -> utils() -> response_success();
	}

	protected function validate_tag(String $tag): bool {
		return preg_match('/^[a-z0-9_]+$/', $tag) && strlen($tag) <= 32;
	}
}
