<?php


namespace Gek\Captcha;


use Gek\Infrastructure\Str;
use function Webmozart\Assert\Tests\StaticAnalysis\null;

class PhraseBuilder
{

    #region fields

    protected int $charLength = 6;

    protected string $allowedChars = 'abcdefghkmnpqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ23456789';

    #endregion fields

    #region ctor

    public function __construct(?int $charLength = null)
    {
        if($charLength !== null){
            $this->charLength = $charLength;
        }
    }

    #endregion ctor

    #region properties

    /**
     * @return int
     */
    public function getCharLength(): int
    {
        return $this->charLength;
    }

    /**
     * @param int $charLength
     * @return PhraseBuilder
     */
    public function setCharLength(int $charLength): PhraseBuilder
    {
        $this->charLength = $charLength;
        return $this;
    }

    /**
     * @return string
     */
    public function getAllowedChars(): string
    {
        return $this->allowedChars;
    }

    /**
     * @param string $allowedChars
     * @return PhraseBuilder
     */
    public function setAllowedChars(string $allowedChars): PhraseBuilder
    {
        $this->allowedChars = $allowedChars;
        return $this;
    }

    #endregion properties

    #region methods

    public function build(?int $charLength = null):string {
        if($charLength == null){
            $charLength = $this->charLength;
        }

        $chars = str_split($this->allowedChars);
        $min = 0;
        $max = count($chars) - 1;

        $phrase = '';

        for ($i = 0; $i < $charLength; $i++){
            $phrase .= $chars[rand($min,$max)];
        }
        return $phrase;
    }

    #endregion methods

    #region statics

    public static function equalsPhrase(string $a, string $b, bool $caseSensitive = true,?string $encoding = null, ?string $language = null){
        if(false === $caseSensitive){

            $a = Str::toLowerCase($a,$encoding,$language);
            $b = Str::toLowerCase($b,$encoding,$language);

        }
        return $a === $b;
    }

    public static function buildPhrase(?int $charLength = null, ?string $allowedChars = null ):string{
        $builder = new self($charLength);
        if(!empty($allowedChars)){
            $builder->setAllowedChars($allowedChars);
        }
        $res = $builder->build();
        $builder = null;
        return $res;

    }

    #endregion statics

}