public function parsePalette(
        $paletteSelector,
        $fields,
        array $subPaletteProperties = [],
        array $selectorFieldNames = [],
        PaletteInterface $palette = null
    ) {
        if (!$palette) {
            $palette = new Palette();
            $palette->setName($paletteSelector);
        }

        $palette->setCondition($this->createPaletteCondition($paletteSelector, $selectorFieldNames));

        // We ignore the difference between field set (separated by ";") and fields (separated by ",").
        $fields = preg_split('~[;,]~', $fields);
        $fields = \array_map('trim', $fields);
        $fields = \array_filter($fields);

        $legend = null;

        foreach ($fields as $field) {
            if (preg_match('~^\{(.*?)(_legend)?(:hide)?\}$~', $field, $matches)) {
                $name = $matches[1];
                if ($palette->hasLegend($name)) {
                    $legend = $palette->getLegend($name);
                } else {
                    $legend = new Legend($matches[1]);
                    $palette->addLegend($legend);
                }
                if (\array_key_exists(3, $matches)) {
                    $legend->setInitialVisibility(false);
                }

                continue;
            }

            // Fallback for incomplete palettes without legend,
            // Create an empty legend.
            if (!$legend) {
                $name = 'unnamed';
                if ($palette->hasLegend($name)) {
                    $legend = $palette->getLegend($name);
                } else {
                    $legend = new Legend($matches[1]);
                    $palette->addLegend($legend);
                }
            }

            // Add the current field to the legend.
            $property = new Property($field);
            $legend->addProperty($property);

            // Add sub palette fields to the legend.
            if (isset($subPaletteProperties[$field])) {
                foreach ($subPaletteProperties[$field] as $property) {
                    $legend->addProperty(clone $property);
                }
            }
        }

        return $palette;
    }