<?php

namespace Ig\IgChart\Utility;

use TYPO3\CMS\Core\SingletonInterface;

class ChartUtility implements SingletonInterface
{
    private $id = 0;

    public function getId()
    {
        $this->id++;
        return $this->id;
    }
  

    /**
     * Converts hex to rgba. This is used to set the color inside of the
     * chart.js datasets correctly.
     *
     * Example:
     * hex2rgba('#FFBDAD', 0.5) = rgba(255,189,173,0.5)
     *
     * @param string $color - A six character hex string
     * @param float $alpha - The alpha value of the color. Default value is 1.
     * @return string
     */
    public function hex2rgba($color, $alpha = 1)
    {
        $default = 'rgb(0,0,0)';
        if (empty($color)) {
            return $default;
        }
        if (!str_contains($color, 'rgba')) {
            if ($color[0] == '#') {
                $color = substr($color, 1);
            }
            if (strlen($color) == 6) {
                $rgb = [
                    hexdec($color[0] . $color[1]),
                    hexdec($color[2] . $color[3]),
                    hexdec($color[4] . $color[5]),
                ];
            } elseif (strlen($color) == 3) {
                $rgb = [
                    hexdec($color[0] . $color[0]),
                    hexdec($color[1] . $color[1]),
                    hexdec($color[2] . $color[2]),
                ];
            } else {
                return $default;
            }
            if ($alpha > 1) {
                $alpha = 1;
            }
            return 'rgba(' . implode(',', $rgb) . ',' . $alpha . ')';
        }
        $rgba = $this->getRgbFromRgba($color);
        return 'rgba(' . $rgba[0] . ',' . $rgba[1] . ',' . $rgba[2] . ',' . $alpha . ')';
    }
    public function getAlphaFromRgba($color)
    {
        $rgba = explode(',', preg_replace('/[rgba()]/', '', (string) $color));
        return array_pop($rgba);
    }
    public function getRgbFromRgba($color)
    {
        $rgba = explode(',', preg_replace('/[rgba()]/', '', (string) $color));
        array_pop($rgba);
        return $rgba;
    }
    public function getAlphaArray(?string $color = null): array
    {
        if ($color && str_contains($color, 'rgba')) {
            $default = $this->getAlphaFromRgbab($color) ?: 1;
        } else {
            $default = 1;
        }
        return [
            'default' => $default,
            'hover' => round($default * 0.7, 1),
            'special' => round($default * 0.8, 1),
            'border' => round($default * 0.7, 1),
        ];
    }
}
