<?php

declare(strict_types=1);

class VGT_Sub extends IPSModule
{
    public function Create()
    {
        parent::Create();

        // DeviceID
        $this->RegisterPropertyString('DeviceID', '');

        // Eingehende MQTT-Nachrichten
        $this->RegisterVariableString("InputJSON", "MQTT Input", "", 1);
        $this->EnableAction("InputJSON");

        // Ausgehende MQTT-Nachrichten
        $this->RegisterVariableString("OutputJSON", "MQTT Output", "", 2);

        // Statusvariablen
        $this->RegisterVariableFloat('PowerProduction', 'Power Production', '', 10);
        $this->EnableAction('PowerProduction');

        $this->RegisterVariableFloat('StateOfCharge', 'State of Charge', '', 11);
        $this->EnableAction('StateOfCharge');

        $this->RegisterVariableBoolean('IsRunning', 'Is Running', '', 12);
        $this->EnableAction('IsRunning');

        $this->RegisterVariableBoolean('IsReady', 'Is Ready', '', 13);
        $this->EnableAction('IsReady');

        $this->RegisterVariableFloat('MinSoc', 'Min SoC', '', 14);
        $this->EnableAction('MinSoc');

        $this->RegisterVariableFloat('MaxSoc', 'Max SoC', '', 15);
        $this->EnableAction('MaxSoc');

        // Remote-Control
        $this->RegisterVariableInteger('PowerSetpoint', 'Power Setpoint', '', 20);
        IPS_SetVariableCustomAction($this->GetIDForIdent('PowerSetpoint'), 0);

        $this->RegisterVariableString('Strategy', 'Strategy', '', 21);
        IPS_SetVariableCustomAction($this->GetIDForIdent('Strategy'), 0);
    }

    public function RequestAction($Ident, $Value)
    {
        if ($Ident === "InputJSON") {
            SetValueString($this->GetIDForIdent("InputJSON"), $Value);
            $this->ProcessIncoming($Value);
            return;
        }

        SetValue($this->GetIDForIdent($Ident), $Value);
    }

    private function ProcessIncoming($jsonString)
    {
        $data = @json_decode($jsonString, true);
        if (!is_array($data)) {
            return;
        }

        if (!isset($data['topic']) || !isset($data['payload'])) {
            return;
        }

        $topic   = $data['topic'];
        $payload = $data['payload'];

        $device = $this->ReadPropertyString('DeviceID');

        // Feedback Request
        if ($topic === "feedback-request/$device") {
            $this->SendFeedback($device);
            return;
        }

        // Remote Control Request
        if ($topic === "remote-control-request/$device") {
            $this->ProcessRemoteControl($device, $payload);
            return;
        }
    }

    private function SendFeedback($device)
    {
        $response = [
            "power_production" => GetValue($this->GetIDForIdent('PowerProduction')),
            "state_of_charge"  => GetValue($this->GetIDForIdent('StateOfCharge')),
            "is_running"       => GetValue($this->GetIDForIdent('IsRunning')),
            "is_ready"         => GetValue($this->GetIDForIdent('IsReady')),
            "min_soc"          => GetValue($this->GetIDForIdent('MinSoc')),
            "max_soc"          => GetValue($this->GetIDForIdent('MaxSoc'))
        ];

        SetValueString(
            $this->GetIDForIdent("OutputJSON"),
            json_encode([
                "topic"   => "feedback-response/$device",
                "payload" => json_encode($response)
            ])
        );
    }

    private function ProcessRemoteControl($device, $payload)
    {
        $json = @json_decode($payload, true);
        if (!is_array($json)) {
            return;
        }

        if (isset($json['power_setpoint'])) {
            SetValue($this->GetIDForIdent('PowerSetpoint'), (int)$json['power_setpoint']);
        }

        if (isset($json['strategy'])) {
            SetValueString($this->GetIDForIdent('Strategy'), (string)$json['strategy']);
        }

        SetValueString(
            $this->GetIDForIdent("OutputJSON"),
            json_encode([
                "topic"   => "remote-control-response/$device",
                "payload" => json_encode($json)
            ])
        );
    }
}

?>