<?php
use Workerman\Worker;
use Workerman\Connection\TcpConnection;
use Workerman\Protocols\Http\Request;
use Workerman\Protocols\Http\Response;
require_once __DIR__ . '/vendor/autoload.php';

use EdgeManager\EDataCapture\{ EDataCapture, ENodeConfigure };

$options = getopt('h::', ['server_name:', 'user:', 'password:', 'help::']);

init_db($options['server_name'], $options['user'], $options['password']);

$worker = new Worker('http://0.0.0.0:8888');
$worker -> name = 'CaptureWorker';

$worker -> onWorkerStart = function(Worker $worker) {
    global $options, $dbconn;

    $dbconn = pg_connect(sprintf(  "host=%s dbname=scada user=%s password=%s",
                                    $options['server_name'], $options['user'], $options['password']));
};

$worker -> onMessage = function(TcpConnection $connection, Request $request) {
    global $options, $dbconn;

    $post = $request -> post();
    if (isset($post['action']) and str_contains($post['action'], 'node')) {
        $action = $post['action'];
        unset($post['action']);
        $enode_configure = new ENodeConfigure($dbconn, $post = $post);
        $res = $enode_configure -> $action();
        if ($res === true)
            $connection -> send(json_encode(array(
                'code'  => 0,
                'msg'   => 'Success'
            )));
        else if ($res === "REPLICATED")
            $connection -> send(json_encode(array(
                'code'  => 1,
                'msg'   => '节点编码不可重复！'
            )));
        else if ($res === false) {
            $connection -> send(json_encode(array(
                'code'  => 1,
                'msg'   => '服务器内部逻辑错误，请联系开发者！'
            )));
        }
    } else if (isset($post['action']) and str_contains($post['action'], 'data')) {
        $action = $post['action'];
        unset($post['action']);
        $data_capture = new EDataCapture($dbconn, $post = $post);
        $res = $data_capture -> $action();
        if ($res === true) {
            $connection -> send(json_encode(array(
                'action' => 'result_set_data',
                'errcode' => 0,
                'errmsg' => ''
            )));
        } else {
            $connection -> send(json_encode(array(
                'action' => 'result_set_data',
                'errcode' => 4002,
                'errmsg' => 'ROLLBACKed: Bad data received (structure and/or values)'
            )));
        }
    }

    $get = $request -> get();
    if (isset($get['query']) and $get['query'] == 'nodes') {
        $enode_configure = new ENodeConfigure($dbconn, $get = $get);
        $nodes = $enode_configure -> get_nodes();
        if (is_null($nodes))
            $connection -> send(json_encode(array(
                'code'  => 1,
                'msg'   => 'no node data'
            )));
        else
            $connection -> send(json_encode(array(
                'code'  => 0,
                'data'  => $nodes
            )));
    }
};

Worker::runAll();
