<?php

class RSOnlineClient extends BackgroundBaseClient {
    public function login() {
        $username = $this->prop['username'];
        $password = $this->prop['password'];
        $params = [
            "header"=>[
                'Content-Type'=>'application/json',
            ],
            "json" => [
                "userName" => $username,
                "password" => $password
            ]
        ];

        //region LOG Definition
        $this->setApiName("rsonline-login");
        $this->setLogParams([
            'username' => $username,
            'password' => $password
        ]);
        //endregion

        try {
            $i = 1;
            $response = false;
            while (!$response && $i < 10) {
                $response = $this->tryLogin($params);
                $i++;
            }

            if ($response["status"] && array_key_exists('data', $response) && array_key_exists('access_token', $response['data'])) {
                return $response['data']['access_token'];
            } else if (!$response["status"] && array_key_exists('message', $response) && array_key_exists('message', $response)){
                throw new CustomErrorException(BaseResponse::INVALID_AUTHENTICATION_AUTHORIZATION, $response['message']);
            } else {
                throw new CustomErrorException(BaseResponse::INVALID_AUTHENTICATION_AUTHORIZATION, "Reason Unknown");
            }
        } catch (\Exception $e) {
            throw new CustomErrorException(BaseResponse::INVALID_AUTHENTICATION_AUTHORIZATION, "Gagal melakukan login RS Online [" . $e->getMessage() . "]");
        }
    }

    private function tryLogin($params)
    {
        try {
            return $this->execute("POST", "api/login", $params, false);
        } catch (\Exception $e) {
            return false;
        }
    }

    private function getExistingToken(): string
    {
        return ApiToken::findTokenOrCreateOne(ApiToken::KEY_RS_ONLINE, "9 minutes", array($this, "login"));
    }

    private function handleResponse($method, $path, $params) {
        try {
            $response = $this->execute($method, $path, $params, false);
            if ($response['status'] && array_key_exists('data', $response)) {
                $result = $response['data'];
            } else if (array_key_exists('message', $response)){
                $result = [
                    "message" => $response["message"]
                ];
            } else {
                $result = [
                    "message" => "Data tidak ditemukan"
                ];
            }
        } catch (CustomErrorException $e) {
            $result = [
                "message" => $e->getMessages()
            ];
        } catch (\Exception $e) {
            $result = [
                "message" => $e->getMessage()
            ];
        }

        return $result;
    }

    /**
     * @param $query
     * @return mixed
     * @throws CustomErrorException
     * response:
     * {
     *  "status": true,
     *  "message": "data found",
     *  "pagination": {
     *      "total_number_of_pages": 32,
     *      "current_page": 1,
     *      "next": {
     *          "page": 2,
     *          "limit": 100
     *      }
     *  },
     *  "data": [{}, {}, ...]
     * }
     */
    public function rumahSakits($query) {
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->getExistingToken()
            ],
            "query" => $query
        ];

        //region LOG Definition
        $this->setApiName("rsonline-rumahsakit");
        $this->setLogParams($query);
        //endregion

        return $this->execute("GET", "api/rumahsakit", $params, false);
    }

    public function rumahSakit($id) {
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->getExistingToken()
            ]
        ];

        //region LOG Definition
        $this->setApiName("rsonline-rumahsakit-$id");
        $this->setLogParams([
            'id' => $id
        ]);
        //endregion

        return $this->execute("GET", "api/rumahsakit/$id", $params, false);
    }

    /**
     * @param $query
     * @return mixed
     * @throws CustomErrorException
     * response:
     * {
     *  "status": true,
     *  "message": "data found",
     *  "pagination": {
     *      "total_number_of_pages": 7,
     *      "current_page": 1,
     *      "next": {
     *          "page": 2,
     *          "limit": 100
     *      }
     *  },
     *  "data": [{}, {}, ...]
     * }
     */
    public function ketersediaanTempatTidur($query) {
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->getExistingToken()
            ],
            "query" => $query
        ];

        //region LOG Definition
        $this->setApiName("rsonline-ketersediaan-tempat-tidur");
        $this->setLogParams($query);
        //endregion

        return $this->execute("GET", "api/ketersediaantempattidur", $params, false);
    }

    public function ketersediaanNakes($query, $doCaching = false) {
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->getExistingToken()
            ],
            "query" => $query
        ];

        //region LOG Definition
        $this->setApiName("rsonline-ketersediaan-nakes");
        $this->setLogParams($query);
        //endregion

        // todo passing $doCaching
        return $this->execute("GET", "api/ketersediaannakes", $params, false);
    }

    public function ketersediaanPelayanan($query, $doCaching = false) {
        $params = [
            "headers" => [
                "Authorization" => "Bearer " . $this->getExistingToken()
            ],
            "query" => $query
        ];

        //region LOG Definition
        $this->setApiName("rsonline-ketersediaan-pelayanan");
        $this->setLogParams($query);
        //endregion

        // todo passing $doCaching
        return $this->execute("GET", "api/ketersediaanpelayanan", $params, false);
    }

    public function doPost($path, $params) {
        //region LOG Definition
        $this->setApiName("rsonline-doPost");
        $this->setLogParams($params);
        //endregion

        return $this->execute("POST", $path, $params, false);
    }

    public function doGet($path, $params) {
        //region LOG Definition
        $this->setApiName("rsonline-doGet");
        $this->setLogParams($params);
        //endregion

        return $this->execute("GET", $path, $params, false);
    }
}
