<?php
namespace nur\ldap;

use Iterator;
use nur\iter;

trait TLdapWalker {
  function __construct(?LdapConn $conn=null, ?LdapSearch $search=null) {
    parent::__construct(null, null, null, $conn);
    if ($search !== null) $this->resetSearch($search);
  }

  /** @var LdapSearch */
  protected $search;

  function resetSearch(LdapSearch $search): ILdapWalker {
    $this->close();
    $this->reset(null, null, $search->getAttrs());
    $this->search = $search;
    return $this;
  }

  /** @var Iterator */
  protected $it;

  protected function loadNext(): bool {
    $it = $this->it;
    if (!$it->valid()) {
      $this->close();
      return false;
    }
    $this->load($it->key(), $it->current());
    return true;
  }

  function next(?bool &$found=null): bool {
    if ($this->it === null) {
      $this->it = $this->search->getIterator();
      $this->it->rewind();
      $updateFound = true;
    } else {
      $this->it->next();
      $updateFound = false;
    }
    $haveNext = $this->loadNext();
    if ($updateFound) $found = $haveNext;
    return $haveNext;
  }

  function close(): void {
    iter::close($this->it);
    $this->it = null;
  }
}
