<?php

namespace DetailTask;

use ApiToken;
use LogHelper;
use PipMadrasahClient;

/**
 * @property PipMadrasahClient $client
 */
class PipMadrasahTask extends AbstractTask {
    #region Attributes
    #endregion

    #region Main
    public function init()
    {
        $this->client = new PipMadrasahClient($this->config["pipmadrasah_prop"], $this);
        $this->client->setLogger($this->logger);
        $this->processName = "Process PIP Madrasah Token";
    }

    /**
     * @return void
     * Logging disimpan ke table api_errors
     */
    public function processToken() {
        $this->init();
        $startTime = microtime(true);
        try {
            $this->retrieveAndDeleteOldToken();
            $this->retrieveAndSaveNewToken();
            LogHelper::logInfo(
                $this->processName . " ended successfully",
                $startTime,
                microtime(true),
                [],
                self::LOG_TYPE,
                $this->logger
            );
        } catch (\Exception $e) {
            LogHelper::logInfo(
                $this->processName . " ended with exception",
                $startTime,
                microtime(true),
                [$e->getMessage()],
                self::LOG_TYPE,
                $this->logger
            );
        }

    }
    #endregion

    #region Helper
    private function retrieveAndDeleteOldToken() {
        //check Count API token for PIP_MADRASAH
        $pipMadrasahToken = ApiToken::count([
            'conditions' => 'api_name = ?0 ',
            'bind' => [
                'PIP_MADRASAH'
            ]
        ]);

        //IF Count > 1 then remove the old token
        if($pipMadrasahToken > 1) {
            $oldToken = ApiToken::findFirst([
                'conditions' => 'api_name = ?0',
                'bind' => [
                    'PIP_MADRASAH'
                ]
            ]);
            $dQuery = "DELETE FROM jaga.api_token WHERE api_name = 'PIP_MADRASAH' AND token = '" .$oldToken->token . "'";
            $this->rawQuery($dQuery);
        }
    }

    private function retrieveAndSaveNewToken() {
        $newToken = $this->client->login();
        $newDataToken = new ApiToken();
        $newDataToken->api_name = 'PIP_MADRASAH';
        $newDataToken->token = $newToken;
        $newDataToken->save();
    }
    #endregion
}
