<?php

namespace ControlScripts\Scopes;

use \SHServ\Entities\Device;

class SpotlightsScope extends \SHServ\Middleware\ControlScripts implements \SHServ\Implements\ControlScriptsInterface {
	public function register_sync_map(): void {
		$this -> add_sync_connection([
			["type" => "relay", "alias" => "spotlight_main_back_1", "channel" => 0],
			["type" => "button", "alias" => "buttons_backdoor", "channel" => 0],
			["type" => "button", "alias" => "master_door_btns", "channel" => 0],
		]);

		$this -> add_sync_connection([
			["type" => "relay", "alias" => "spotlight_main_back_2", "channel" => 0],
			["type" => "button", "alias" => "buttons_backdoor", "channel" => 1],
			["type" => "button", "alias" => "master_door_btns", "channel" => 1],
		]);

		$this -> add_sync_connection([
			["type" => "relay", "alias" => "spotlight_main_front_1", "channel" => 0],
			["type" => "button", "alias" => "buttons_backdoor", "channel" => 2],
			["type" => "button", "alias" => "master_door_btns", "channel" => 2],
		]);
	}

	public function register_events_handlers(): void {
		$this -> btns_click_handlers("buttons_backdoor");
		$this -> btns_click_handlers("master_door_btns");
		$this -> on_online("buttons_backdoor");
		$this -> on_online("master_door_btns");
	}

	public function register_actions_scripts(): void {
		$this -> add_action_script([
			"alias" => "spotlights_on",
			"name" => "All Spotlights On",
			"icon" => '<i class="ph ph-headlights"></i>',
			"description" => "Включить все прожекторы",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> all_spotlight_switch(true);
		});

		$this -> add_action_script([
			"alias" => "spotlights_off",
			"name" => "All Spotlights Off",
			"icon" => '<i class="ph ph-headlights"></i><i class="ph ph-x"></i>',
			"description" => "Выключить все прожекторы",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> all_spotlight_switch(false);
		});

		$this -> add_action_script([
			"alias" => "front_spotlight_on",
			"name" => "ВКЛ фронтальный прожектор",
			"icon" => '<i class="ph ph-headlights"></i>',
			"description" => "Включить только фронтальный прожектор на главном входе",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> spotlight_switch("spotlight_main_front_1", true);
		});

		$this -> add_action_script([
			"alias" => "front_spotlight_off",
			"name" => "ВЫКЛ фронтальный прожектор",
			"icon" => '<i class="ph ph-headlights"></i>',
			"description" => "Выключить только фронтальный прожектор на главном входе",
			"author" => "Eugene Sukhodolskiy"
		], function($params) {
			return $this -> spotlight_switch("spotlight_main_front_1", false);
		});
	}

	public function register_regular_scripts(): void {
		$this -> add_regular_script([
			"alias" => "spotlights_by_time",
			"name" => "Spotlights by Time",
			"description" => "Управление уличными прожекторами по времени",
			"author" => "Eugene Sukhodolskiy"
		], function () {
			$tz = new \DateTimeZone('Europe/Kyiv');

			$now = new \DateTime('now', $tz);
			$from = new \DateTime('9:00', $tz);
			$to = new \DateTime('16:30', $tz);

			if ($now >= $from && $now <= $to) {
				$this -> all_spotlight_switch(false);
			}
		});
	}

	// ACTIONS

	protected function spotlight_switch(String $relay_alias, Bool $state = false) {
		$device_entries = $this -> helper() -> get_sync_entries_by_type($this -> sync_map(), "relay");

		$relay_api = $this -> devices() -> by_alias($relay_alias) -> device_api();
		$result = false;
		if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay) {
			$result = $relay_api -> set_state($state);
			$this -> helper() -> sync_relay_to_btns($this -> sync_map(), $relay_alias);
		}

		return [
			"result" => $result
		];
	}
	
	protected function all_spotlight_switch(Bool $state = false): Array {
		$results = [];
		$device_entries = $this -> helper() -> get_sync_entries_by_type($this -> sync_map(), "relay");

		foreach($device_entries as $device_entry) { 
			$relay_api = $this -> devices() -> by_alias($device_entry["alias"]) -> device_api();
			$result = false;
			$ch = $device_entry["channel"];

			if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay) {
				$status = $relay_api -> get_status();

				if(isset($status["channels"][$ch]["state"]) and $status["channels"][$ch]["state"] != ($state ? "on" : "off")) {
					$result = $relay_api -> set_state($state);
				}
			}

			$results[$device_entry["alias"]] = $result;
			$this -> helper() -> sync_relay_to_btns($this -> sync_map(), $device_entry["alias"]);
		}
		

		return [
			"devices" => $results
		];
	}

	// EVENTS HANDLERS

	protected function on_online($alias) {
		$this -> add_event_handler("button@{$alias}.online", function(Device $btns_block, Array $data) {
			$btns_block_api = $btns_block -> device_api();
			if($btns_block_api instanceof \SHServ\Tools\DeviceAPI\Button) {
				$btns_block_api -> set_channel_state("mute", 3);
			}

			$this -> helper() -> sync_btn_channels($this -> sync_map(), $btns_block -> alias);
		});
	}

	protected function btns_click_handlers($alias): void {
		$self = $this;
		$buttons = $this -> helper() -> prepare_sync_map_by_alias($this -> sync_map(), $alias);
		foreach($buttons as $btn_channel => $entry) { 
			if($entry[0]["type"] != "relay") {
				continue;
			}

			$relay_alias = $entry[0]["alias"];
			$relay_channel = $entry[0]["channel"];

			$this -> add_event_handler("button@{$alias}({$btn_channel}).press", function(Device $btns_block, Array $data) use ($self, $btn_channel, $relay_alias, $relay_channel) {
				$btns_block_api = $btns_block -> device_api();
				$relay_api = $this -> devices() -> by_alias($relay_alias) -> device_api();

				if($relay_api instanceof \SHServ\Tools\DeviceAPI\Relay and $btns_block_api instanceof \SHServ\Tools\DeviceAPI\Button) {
					$relay_api -> toggle_channel($relay_channel);
					$this -> helper() -> sync_relay_to_btns($this -> sync_map(), $relay_alias);
				}
			});
		}
	}
}
