<?php

namespace ControlScripts;

use \SHServ\Entities\Device;

class TestScriptsScope extends \SHServ\Middleware\ControlScripts implements \SHServ\Implements\ControlScriptsInterface {
	public function register_events_handlers(): void {
		$this -> stand_btn_pressed_to_stand_relay();
	}

	public function register_regular_scripts(): void {
		$this -> add_regular_script("testing1", function() {
			$button = $this -> devices() -> by_alias("test_device_btn");
			$btn_api = $button -> device_api();
			
			if($btn_api instanceof \SHServ\Tools\DeviceAPI\Button) {
				if(($btn_api -> get_status())["channels"][1]["indicator"] != "warning") {
					$btn_api -> set_channel_state("warning", 1);
				} else {
					$btn_api -> set_channel_state("mute", 1);
				}
			}
		});

		$this -> add_regular_script("testing2", function() {
			$button = $this -> devices() -> by_alias("test_device_btn");
			$btn_api = $button -> device_api();
			
			if($btn_api instanceof \SHServ\Tools\DeviceAPI\Button) {
				if(($btn_api -> get_status())["channels"][2]["indicator"] != "error") {
					$btn_api -> set_channel_state("error", 2);
				} else {
					$btn_api -> set_channel_state("mute", 2);
				}
			}
		});
	}

	// EVENTS HANDLERS
	
	protected function stand_btn_pressed_to_stand_relay() {
		$this -> add_event_handler("button.press", function(Device $device, Array $data) {
			$channel = intval($data["channel"]);

			switch($channel) {
				case 0:
					$relay = $this -> devices() -> by_alias("test_device_relay");
					$relay -> device_api() -> toggle_channel($channel);

					$relay_channels = ($relay -> device_api() -> get_status())["channels"];

					$device_api = $device -> device_api();
					if($device_api instanceof \SHServ\Tools\DeviceAPI\Button) {
						$device_api -> set_channel_state(
							$relay_channels[$channel]["state"] == "on" ? "enabled" : "disabled", 
							$channel
						);
					}
				case 1: 
					$relay = $this -> devices() -> by_alias("test_back_street_light");
					$relay -> device_api() -> toggle_channel(0);
					$relay_channels = ($relay -> device_api() -> get_status())["channels"];

					$device_api = $device -> device_api();
					if($device_api instanceof \SHServ\Tools\DeviceAPI\Button) {
						$device_api -> set_channel_state(
							$relay_channels[0]["state"] == "on" ? "enabled" : "disabled", 
							$channel
						);
					}
				break;
			}
			
		});
	}
}