<?php
declare(strict_types=1);

namespace AuxCF\Entities\Field\Traits;

use AuxCF\Entities\Field\Enum\ChoicesFieldLayoutEnum;
use AuxCF\Entities\Field\Enum\ChoicesFieldReturnFormatEnum;
use AuxCF\Entities\Settings\Traits\EnumPropertyTraits;

trait ChoicesFieldTraits
{
  use EnumPropertyTraits;

  protected mixed $choices;
  protected ChoicesFieldReturnFormatEnum $returnFormat = ChoicesFieldReturnFormatEnum::DEFAULT;
  protected ChoicesFieldLayoutEnum $layout = ChoicesFieldLayoutEnum::DEFAULT;

  public function setChoices(mixed $choices): self
  {
    $this->choices = $choices;
    return $this;
  }

  public function setReturnFormat(string|ChoicesFieldReturnFormatEnum $returnFormat): self
  {
    $this->setEnumProperty(ChoicesFieldReturnFormatEnum::class, $returnFormat, 'returnFormat');
    return $this;
  }

  public function setLayout(string|ChoicesFieldLayoutEnum $layout): self
  {
    $this->setEnumProperty(ChoicesFieldLayoutEnum::class, $layout, 'layout');
    return $this;
  }

  public function getChoicesOptionsArray(): array
  {
    if ($this->choices instanceof \Closure) {
      return call_user_func($this->choices);
    } elseif (is_string($this->choices)) {
      return $this->choices::getIndexedOptions();
    } else {
      return $this->choices;
    }
  }

  protected function getChoicesArray(): array
  {
    $array = [
      'choices' => $this->getChoicesOptionsArray(),
      'return_format' => $this->returnFormat->value,
    ];

    if ('select' !== $this->type->value) {
      $array['layout'] = $this->layout->value;
    }

    return $array;
  }
}
