<?php

namespace app\entity\gateway\ws;

use app\entity\gateway\script\BaseScript;
use app\enum\gateway\message\{ScriptEnum, SystemEnum};

class OutMessage
{
    private string $type;
    private string $event;
    private array $data;

    public function __construct(
        BaseScript|ScriptEnum|SystemEnum|array $event,
        mixed                                  $data = []
    )
    {
        // 通过Base::create();创建的
        if (is_array($event) && count($event) == 3) {
            $this->type = $event[0];
            $this->event = $event[1];
            $this->data = is_array($data) ? array_merge($data, $event[2]) :  $event[2];
            return;
        } else if ($event instanceof ScriptEnum) {
            $this->type = 'script';
            $this->event = $event->value;
        } else if ($event instanceof SystemEnum) {
            $this->type = 'system';
            $this->event = $event->value;
        }
        // data处理
        if ($data instanceof BaseScript) {
            $this->data = $data->toArray();
        } else {
            $this->data = (array)$data;
        }
    }

    public function toJson(): string
    {
        return json_encode([
            'type' => $this->type,
            'event' => $this->event,
            'data' => $this->data,
        ], JSON_UNESCAPED_UNICODE);
    }
}