<?php

/*
 * This file is part of the AuthStack project.
 *
 * (c) Buckhill Ltd <development@buckhill.co.uk>
 *
 * This source file is subject to the Buckhill license that is bundled
 * with this source code in the file LICENSE.
 */

namespace Buckhill\LDAP;


class EntryCollection
{
    protected $size = 0;
    protected $cnt = 0;
    protected $entries = [];
    protected $index = [];
    protected $attributes = [];

    public static function fromArray(array $results = null)
    {
        $me = new static;

        if(!is_null($results) && sizeof($results))
        {
            foreach($results as $name => $values)
            {
                if(is_array($values))
                {
                    $me->add(Entry::fromRecord($name, $values));
                }
            }
        }

        return $me;
    }


    /**
     * @return array
     */
    public function toArray()
    {
        $result = [];

        $entries = $this->entries;

        if(is_array($entries) && sizeof($entries))
        {
            foreach($entries as $entry)
            {
                /** @var $entry Entry */
                $result[$entry->getName()] = $entry->getValue();
            }
        }


        return $result;
    }



    /**
     * @return int
     */
    public function size()
    {
        return sizeof($this->index);
    }


    /**
     * @return int
     */
    public function count()
    {
        return $this->size();
    }


    /**
     * @return array
     */
    public function all()
    {
        return $this->entries;
    }

    /**
     * @return array
     */
    public function getAttributeNames()
    {
        return $this->attributes;
    }

    /**
     * @param Entry $entry
     *
     * @return $this
     */
    public function add(Entry $entry)
    {
        $this->entries[$this->cnt] = $entry;
        $this->index[sha1($entry->getName(), true)] = $this->cnt;
        $this->attributes[] = $entry->getName();

        $this->cnt++;

        return $this;
    }


    /**
     * @param string $entry
     *
     * @return bool
     */
    public function has($entry = '')
    {
        return isset($this->index[sha1($entry, true)]);
    }


    /**
     * @param string $entry
     * @param        $default
     *
     * @return mixed
     */
    public function get($entry = '', $default = null)
    {
        return $this->has($entry) ? $this->entries[$this->index[sha1($entry, true)]] : $default;
    }
}