<?php

namespace onespace\tools\activeApi\components\clients;

use onespace\tools\activeApi\components\clients\base\BaseOneSpaceClient;
use Yii;
use yii\web\NotFoundHttpException;

/**
 * The client to connect to the OneDevice Microservice
 *
 * Extend from here to add functionality.
 *
 * Add the following to `config/params.php`:
 *
 * ```php
 * 'serviceUrls' => [
 *  ...
 *  'oneDevice' => getenv('SERVICE_URL_ONEDEVICE') ?: 'https://dev.1device.1s.co.za/',
 *  ...
 * ],
 * ```
 */

class OneDeviceClient extends BaseOneSpaceClient {
    public function serverUrl(): string {
        return Yii::$app->params['serviceUrls']['oneDevice'];
    }

    public function setLogicalAddress(int $serial, int $logical): bool {
        $url = $this->serverUrl() . 'v1/gateway/set-address';
        Yii::info($url, __METHOD__);
        $request = $this->getClient()->post($url, [
            'data' => [
                'address' => $logical,
                'serial' => $serial,
            ],
        ]);
        $this->setLastRequest($request);
        $response = $request->send();
        if ($response->isOk) {
            return $response->data['success'];
        }
        return false;
    }

    public function setSite(int $logical, string $site): bool {
        $url = $this->serverUrl() . 'v1/gateway/site';
        Yii::info($url, __METHOD__);
        $request = $this->getClient()->post($url, [
            'data' => [
                'address' => $logical,
                'site' => $site,
            ],
        ]);
        $this->setLastRequest($request);
        $response = $request->send();
        if ($response->isOk) {
            return $response->data['success'];
        }
        return false;
    }

    public function getLogicalAddresses(): array {
        $url = $this->serverUrl() . 'v1/gateway/existing-logical-ids';
        $request = $this->getClient()->get($url);
        $this->setLastRequest($request);
        $response = $request->send();
        if (!$response->isOk) {
            throw new NotFoundHttpException("Cannot get list of existing IDs");
        }
        return $response->data['data'];
    }
}
