<?php

namespace IMATHUZH\Qfq\Core\Form\FormElement;

use IMATHUZH\Qfq\Core\Form\Form;

class ColorPickerFormElement extends AbstractFormElement {

    public function __construct(array $attributes, ?Form $form = null) {
        parent::__construct($attributes, $form);

        // Defaults
        $dataConfig = [];
        $dataConfig[COLOR_PICKER_DEFAULT] = $this->value;
        $dataConfig[COLOR_PICKER_SWATCHES] = [];
        $dataConfig[COLOR_PICKER_PREVIEW] = false;
        $dataConfig[COLOR_PICKER_OPACITY] = false;
        $dataConfig[COLOR_PICKER_INTERACTION_HEX] = true;
        $dataConfig[COLOR_PICKER_INTERACTION_RGBA] = false;
        $dataConfig[COLOR_PICKER_INTERACTION_INPUT] = true;
        $dataConfig[COLOR_PICKER_INTERACTION_CLEAR] = true;

        $userConfig = $this->parseColorPickerConfig($this->attributes[FE_COLOR_PICKER_CONFIG] ?? '');
        // Overwrite defaults with user given values
        foreach ($userConfig as $key => $value) {
            // Skip default if value is set
            if ($key === COLOR_PICKER_DEFAULT && $dataConfig[$key] !== '') continue;

            $dataConfig[$key] = $value;
        }

        // Not user defined Configs
        $dataConfig[COLOR_PICKER_THEME] = 'classic';
        $dataConfig[COLOR_PICKER_DATA_TARGET] = $this->htmlAttributes[HTML_ATTR_NAME];
        $dataConfig[COLOR_PICKER_INTERACTION_SAVE] = true;
        $dataConfig[COLOR_PICKER_DISABLED] = $attributes[FE_MODE] === FE_MODE_READONLY;
        $dataConfig[FE_DYNAMIC_UPDATE] = $attributes[FE_DYNAMIC_UPDATE] === 'yes' ? 'data-load' : '';


        $this->htmlAttributes[COLOR_PICKER_DATA_CONFIG] = htmlspecialchars(json_encode($dataConfig, JSON_UNESCAPED_SLASHES), ENT_QUOTES, 'UTF-8');
    }

    private function parseColorPickerConfig(string $raw): array {
        $parsed = [];

        $pairs = explode('|', $raw);

        foreach ($pairs as $pair) {
            if (!str_contains($pair, ':')) {
                continue; // skip invalid entries
            }

            list($key, $value) = explode(':', $pair, 2);
            $key = trim($key);
            $value = trim($value);

            if ($key === COLOR_PICKER_SWATCHES) {
                $value = explode('+', $value);
            }

            // Auto-cast booleans
            if ($value === 'true') {
                $value = true;
            } elseif ($value === 'false') {
                $value = false;
            }

            $parsed[$key] = $value;
        }

        return $parsed;
    }


}