<?php

namespace app\controllers\v1;

use app\controllers\traits\ProtobufSender;
use app\models\Proto;
use OS\PB\Packet;
use Yii;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\web\Response;

class ApiController extends BaseController {

    use ProtobufSender;

    public $publicEndpoints = [];

    /**
     * {@inheritdoc}
     */
    public function behaviors() {
        return ArrayHelper::merge(
            parent::behaviors(),
            [
                'verbs' => [
                    'class' => VerbFilter::class,
                    'actions' => [
                        'to-protobuf' => ['POST'],
                        'to-json' => ['POST'],
                    ],
                ],
            ]
        );
    }


    /**
     * Convert a JSON string into a protobuf binary string.
     * 
     * @return  yii\web\Response
     * 
     * @access  public
     */

    public function actionToProtobuf(): Response {
        $proto = (new Proto())->jsonToSerializedArray(Yii::$app->request->getRawBody());
        $packet = new Packet();
        $packet->mergeFromJsonString(json_encode($proto));
        return $this->sendProtofbuf($packet->serializeToString());
    }


    /**
     * Convert a binary protobuf string into a deserialized
     * a JSON string.
     * 
     * @return  yii\web\Response
     * 
     * @access  public
     */

    public function actionToJson(): Response {
        try {
            $packet = new Packet();
            $packet->mergeFromString(Yii::$app->request->getRawBody());

            $data = (new Proto())->protoPacketToUnserializedArray($packet);

            return $this->asJson([
                'success' => true,
                'data' => $data,
            ]);
        } catch (\Throwable $th) {
            $return = [
                'success' => false,
                'message' => $th->getMessage(),
            ];

            if (YII_DEBUG) {
                $return['trace'] = $th->getTrace();
            }

            return $this->asJson($return);
        }
    }
}
