<?php
/**
 * Class ApiService
 * User: Nessandro
 * Date: 2019-09-12
 * Time: 10:42
 * @package ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Interfaces
 */

namespace ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Interfaces;


use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Exceptions\ZimbraServiceException;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Client;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\ApiClientHandler;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\ErrorHandler;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\FormDataHandler;
use ModulesGarden\Servers\ZimbraEmail\App\Libs\Zimbra\Components\Api\Soap\Traits\ProcessStepHandler;
use function ModulesGarden\Servers\ZimbraEmail\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 ZimbraServiceException
     */
    protected function throwError($message = 'Service error, contact ModulesGarden to investigate this problem.', $code = 0)
    {
        throw new ZimbraServiceException($message, $code);
    }
}