<?php

namespace Teknisa\Libs\Util;

use Doctrine\DBAL\Connection;
use Zeedhi\Framework\DB\StoredProcedure\Param;
use Zeedhi\Framework\DB\StoredProcedure\StoredProcedure;

class NewCode extends StoredProcedure {

    public function __construct(Connection $connection, $procedureName = 'NOVO_CODIGO') {
        parent::__construct($connection, $procedureName);
    }

    /**
     * Format a code generated by the new code, making cast to int
     * or return the value based on column size.
     *
     * @param      $code
     * @param      $colSize
     * @param bool $castToNumeric
     *
     * @return int|string
     */
    protected function formatValue($code, $colSize, $castToNumeric = false) {
        return $castToNumeric ? (int)$code : substr($code, -1 * $colSize);
    }

    /**
     * Return a code generated by the procedure
     *
     * @param      $tableName
     * @param      $nrorg
     * @param int  $interval
     * @param int  $colSize
     * @param bool $castToNumeric
     *
     * @return int|string
     */
    public function getCodeByTableName($tableName, $nrorg, $interval = 1, $colSize = 10, $castToNumeric = false) {

        $this->addParam(new Param('P_CONTADOR', Param::PARAM_INPUT, $tableName, Param::PARAM_TYPE_STR));
        $this->addParam(new Param('P_SEQUENCIAL', Param::PARAM_OUTPUT, null, Param::PARAM_TYPE_STR, 20));
        $this->addParam(new Param('P_QTDE', Param::PARAM_INPUT, $interval, Param::PARAM_TYPE_INT));
        $this->addParam(new Param('P_NRORG', Param::PARAM_INPUT, $nrorg, Param::PARAM_TYPE_INT));
        $code = $this->execute();

        // clear params
        $this->params = array();

        return $this->formatValue($code['P_SEQUENCIAL'], $colSize, $castToNumeric);

    }
}