<?php

namespace App\Modules\Excell\Types\iRichText;

use PhpOffice\PhpSpreadsheet\RichText\RichText;
use PhpOffice\PhpSpreadsheet\Style\Font;

class RichTextWrapper
{
    public function __construct(
        protected RichText $richText = new RichText,
        protected string $defaultFontName = 'Calibri',
        protected int $defaultSize = 12,
    ) {}

    /**
     * Default font name
     */
    public function setDefaultFont(string $fontname): self
    {
        $this->defaultFontName = $fontname;

        return $this;
    }

    /**
     * Default font size
     */
    public function setDefaultSize(int $size): self
    {
        $this->defaultSize = $size;

        return $this;
    }

    /**
     * Add or attach text
     *
     * @param  array<int, string>  $styles
     */
    public function add(?string $text, array $styles = [], bool $bold = false): self
    {
        if (! $text) {
            return $this;
        }

        $textRun = $this->richText->createTextRun($text);

        $font = $textRun->getFont() ?: new Font;
        $font->setName($this->defaultFontName)
            ->setSize($this->defaultSize);

        if ($bold) {
            $font->setBold(true);
        }

        return $this;
    }

    /**
     * Return RichText
     */
    public function toRichText(): RichText
    {
        return $this->richText;
    }
}
