<?php


namespace Gek\Captcha;


class RgbColor
{
    #region fields

    protected int $r = 0;

    protected int $g = 0;

    protected int $b = 0;

    #endregion fields

    #region ctor

    public function __construct(int $r = 0, int $g = 0, int $b = 0)
    {
        $this->setR($r);
        $this->setG($g);
        $this->setB($b);
    }



    #endregion ctor

    #region properties

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

    /**
     * @param int $r
     * @return RgbColor
     */
    public function setR(int $r): RgbColor
    {
        $this->r = $this->fixValue($r);
        return $this;
    }

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

    /**
     * @param int $g
     * @return RgbColor
     */
    public function setG(int $g): RgbColor
    {

        $this->g = $this->fixValue($g);
        return $this;
    }

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

    /**
     * @param int $b
     * @return RgbColor
     */
    public function setB(int $b): RgbColor
    {
        $this->b = $this->fixValue($b);
        return $this;
    }

    #endregion properties

    #region methods

    /**
     * @return array
     */
    public function toArray(): array
    {
        return [$this->r, $this->g, $this->b];
    }

    /**
     * @return int
     */
    public function toInt(): int
    {
        $res = (int)(($this->r) & 0xFF);
        $res = (int)(( $res << 8 ) | ($this->g & 0xFF));
        $res = (int)(( $res << 8 ) | ($this->b & 0xFF));
        return $res;
    }

    /**
     * @param int $value
     * @return $this
     */
    public function fromInt(int $value): self
    {
        $r = (int)(($value >> 16) & 0xFF);
        $g = (int)(($value >> 8) & 0xFF);
        $b = (int)(($value) & 0xFF);
        $this->setR($r)
            ->setG($g)
            ->setB($b);
        return $this;
    }

    #endregion methods

    #region Utils

    /**
     * @param int $value
     * @return int
     */
    protected function fixValue(int $value): int
    {
        if ($value < 0) {
            $value = 0;
        } elseif ($value > 255) {
            $value = 255;
        }
        return $value;
    }

    #endregion Utils

    #region static

    /**
     * @param int $r
     * @param int $g
     * @param int $b
     * @return static
     */
    public static function create(int $r = 0, int $g = 0, int $b = 0):self {
        return new self($r,$g,$b);
    }

    /**
     * @param int $value
     * @return static
     */
    public static function createFromInt(int $value):self {
        $res = new self();
        $res->fromInt($value);
        return $res;
    }

    #endregion static


}