<?php

/*
TODO:
 + Создание метода для получения state скрипта
 + Вывод списков скриптов с полем state
 + Интегрировать поведение относительно поля state при запуске скриптов. Выключенные скрипты не должны быть запущены.
 - Реализовать апдейт скриптов
 */

namespace SHServ\Controllers;

use \SHServ\Middleware\ControlScripts;
use \SHServ\Models\Scripts;
use \SHServ\Entities\Script;
use \SHServ\Entities\Area;

class ScriptsRESTAPIController extends \SHServ\Middleware\Controller {
	public function run_action_script($alias, $params) {
		$result = ControlScripts::run_action_script($alias, $params);

		if(!$result) {
			return $this -> utils() -> response_error("action_script_not_found");
		}

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

	public function actions_scripts_list() {
		$data = (new Scripts()) -> actions_scripts_list();

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

	public function regular_scripts_list() {
		$data = (new Scripts()) -> regular_scripts_list();

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

	public function scope_list() {
		$scripts_model = new Scripts();
		$scopes = $scripts_model -> get_scopes_list();

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

	public function scope_file($name) {
		$scripts_model = new Scripts();
		$scopes = $scripts_model -> get_scopes_list();

		$file = "";
		foreach($scopes as $scope) {
			if($name != $scope["name"]) {
				continue;
			}

			$file = file_get_contents($scope["path"] . "/" . $scope["filename"]);

			break;
		}

		if(!$file) {
			return $this -> utils() -> response_error("scope_not_found");
		}

		return $file;
	}

	public function scope_update($name, $path, $file) {
		if(!strlen($file)) {
			return $this -> utils() -> response_error("empty_field", ["file"]);
		}

		$scripts_model = new Scripts();
		if(!$scripts_model -> scope_is_exists($name)) {
			return $this -> utils() -> response_error("scope_not_found");
		}

		$filepath = "{$path}/{$name}";
		$filepath = strpos($filepath, ".php") ? $filepath : $filepath . ".php";

		if(!file_exists($filepath)) {
			return $this -> utils() -> response_error("file_not_exists");
		}

		$result = file_put_contents($filepath, $file);
		return $result 
			? $this -> utils() -> response_success(["result" => true])
			: $this -> utils() -> response_error("undefined_error");
	}

	public function scope_remove($name) {
		return (new Scripts()) -> remove_scope($name)
			? $this -> utils() -> response_success()
			: $this -> utils() -> response_error("undefined_error");
	}

	protected function set_script_state(String $type, String $uniq_name, String $state) {
		if($state == "enable") {
			$result = (new Scripts()) -> enable_script($type, $uniq_name);
		} else {
			$result = (new Scripts()) -> disable_script($type, $uniq_name);
		}

		return $result === true
			? $this -> utils() -> response_success()
			: $this -> utils() -> response_error($result);
	}

	public function set_scope_state($uniq_name, $state) {
		return $this -> set_script_state("scope", $uniq_name, $state);
	}

	public function set_regular_script_state($uniq_name, $state) {
		return $this -> set_script_state("regular", $uniq_name, $state);
	}

	public function set_action_script_state($uniq_name, $state) {
		return $this -> set_script_state("action", $uniq_name, $state);
	}

	public function place_in_area($target_id, $place_in_area_id) {
		if($target_id != intval($target_id) or intval($target_id) < 1) {
			return $this -> utils() -> response_error("invalid_id", ["target_id"]);
		}

		if($place_in_area_id != intval($place_in_area_id) or intval($place_in_area_id) < 1) {
			return $this -> utils() -> response_error("invalid_id", ["place_in_area_id"]);
		}

		$device = new Script(intval($target_id));
		$place_area = new Area(intval($place_in_area_id));

		if(!$device) {
			return $this -> utils() -> response_error("device_not_found");
		}

		if(!$place_area) {
			return $this -> utils() -> response_error("area_not_exists");
		}

		if(!$device -> place_in_area($place_area)) {
			return $this -> utils() -> response_error("undefined_error");
		}

		return $this -> utils() -> response_success();
	}

	public function unassign_from_area($target_id) {
		if($target_id != intval($target_id) or intval($target_id) < 1) {
			return $this -> utils() -> response_error("invalid_id", ["target_id"]);
		}

		$script = new Script(intval($target_id));

		if(!$script) {
			return $this -> utils() -> response_error("script_not_exists");
		}

		return $script -> place_in_area_id(0)
			? $this -> utils() -> response_success()
			: $this -> utils() -> response_error("undefined_error");
	}
}