<?php
namespace nulib\ldap;


use nulib\ldap\syntaxes\CompositeSyntax;

/**
 * Class CompositeAttr: une liste de valeurs composites
 */
class CompositeAttr extends LdapAttr {
  function reset(?array &$values): self {
    if ($values !== null) {
      /** @var CompositeSyntax $syntax */
      $syntax = $this->syntax;
      $tmp = [];
      foreach ($values as $value) {
        $cvalue = $syntax->ldap2php($value);
        $key = $cvalue->getKey();
        $value = $cvalue->formatLdap();
        $tmp[$key] = $value;
      }
      $values = $tmp;
    }
    $this->data =& $values;
    return $this;
  }

  function add($value, bool $unique=true, bool $strict=false): self {
    /** @var CompositeSyntax $syntax */
    $syntax = $this->syntax;
    $value = A::first($syntax->ensureArray($value));
    $cvalue = $syntax->ensureComposite($value);
    if ($cvalue !== null) {
      $key = $cvalue->getKey();
      $value = $cvalue->formatLdap();
      $this->data[$key] = $value;
    }
    return $this;
  }

  function del($value, int $maxCount=-1, bool $strict=false): self {
    if ($value !== null && $this->data !== null) {
      /** @var CompositeSyntax $syntax */
      $syntax = $this->syntax;
      $value = A::first($syntax->ensureArray($value));
      $cvalue = $syntax->ensureComposite($value);
      if ($cvalue !== null) {
        $key = $cvalue->getKey();
        unset($this->data[$key]);
      }
    }
    return $this;
  }

  function ins(int $index, $value): self {
    throw IllegalAccessException::not_allowed("composite attrs don't use indexes");
  }
  function unset(int $index): self {
    throw IllegalAccessException::not_allowed("composite attrs don't use indexes");
  }
}
