<?php
namespace EdgeManager\EController;

class ECommand {
    function __construct(
        protected $dbconn,
        protected $post = NULL,
    ) {}

    function exec() {
        $command2API = [
            'server_restart' => '/Admin/ServerCloseAndRestart',
            'server_close' => '/Admin/ServerClose',
            'device_stop' => '/Edge/DeviceStopRequest',
            'device_continue' => '/Edge/DeviceContinueRequest'
        ];

        $res = pg_query($this -> dbconn, sprintf(
            "SELECT url, port
            FROM hf_mes_scada_edgeserver_controller_server
            WHERE id = '%s'",
            $this -> post -> server_id
        ));
        $server_info = pg_fetch_row($res);

        if (str_starts_with($this -> post -> command, 'server')) {
            $ch = curl_init(
                $server_info[0]
                . ":"
                . $server_info[1]
                . $command2API[$this -> post -> command]
            );
            curl_setopt($ch, CURLOPT_POST, 1);
        } else if (str_starts_with($this -> post -> command, 'device')) {
            $ch = curl_init(
                $server_info[0]
                . ":"
                . $server_info[1]
                . $command2API[$this -> post -> command]
                . '?data='
                . $this -> post -> device_name
            );
        } else {
            return;
        }

        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
        curl_setopt($ch, CURLOPT_HEADER, 1);
        curl_setopt(
            $ch,
            CURLOPT_USERPWD,
            $this -> post -> username
            . ":"
            . $this -> post -> password
        );
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        $return = curl_exec($ch);
        curl_close($ch);
        if ($return) {
            pg_update(
                $this -> dbconn,
                "hf_mes_scada_edgeserver_controller_server",
                ['updated'  => false],
                ['id'       => $this -> post -> server_id]
            );
        }

        pg_insert(
            $this -> dbconn,
            'hf_mes_scada_edgeserver_controller_command',
            [
                'server_id' => $this -> post -> server_id,
                'device_name' => $this -> post -> server_id ?? NULL,
                'command'   => $this -> post -> command,
                'success'   => $return
            ],
        );
    }
}