<?php
/**
 * Class ApiService
 * User: ThurData
 * Date: 2019-09-12
 * Time: 10:42
 * @package ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Interfaces
 */

namespace ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Interfaces;


use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Exceptions\KerioServiceException;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Client;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\ApiClientHandler;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\ErrorHandler;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\FormDataHandler;
use ThurData\Servers\KerioEmail\App\Libs\Kerio\Components\Api\Soap\Traits\ProcessStepHandler;
use function ThurData\Servers\KerioEmail\Core\Helper\response;

class ApiService
{
    use ApiClientHandler;
    use FormDataHandler;
    use ProcessStepHandler;
    use ErrorHandler;

    /**
     * ApiService constructor.
     * @param Client|null $api
     */
    public function __construct(Client $api = null )
    {
        if($api)
        {
            $this->setApi($api);
        }
    }

    /**
     * configure service
     */
    protected function config()
    {
        //todo
    }

    /**
     * Check if service is valid
     *
     * @return bool
     */
    protected function isValid()
    {
        /**
         * check if api is set
         */
        if(!$this->api)
        {
            $this->setError('API Not Found');
            return false;
        }

        return true;
    }

    /**
     * main process of service
     *
     * @return mixed
     */
    protected function process()
    {
        //todo
    }

    /**
     * clear data after service
     */
    protected function clear()
    {

    }

    /**
     * Run process of service
     *
     * @return bool|void
     */
    public function run()
    {

        $this->config();

        if($result = $this->isValid())
        {
            $result = $this->process();
        }

        $this->clear();

        return $result;
    }

    /**
     *
     * @description catch exceptions
     * @return bool|string|void
     */
    public function safeRun()
    {
        try{
            return $this->run();
        }catch (\Exception $e){
            return $e->getMessage();
        }
    }


    /**
     * @description run if you want to return some error
     * @param string $message
     * @param int $code
     * @throws KerioServiceException
     */
    protected function throwError($message = 'Service error, contact ThurData to investigate this problem.', $code = 0)
    {
        throw new KerioServiceException($message, $code);
    }
}