<?php

namespace AuthStack\SP;


use LightSaml\Model\Assertion\NameID;
use LightSaml\Model\Assertion\Assertion;
use LightSaml\Model\Assertion\Attribute;

class AttributeCollection
{
    protected $name_id;
    protected $index = [];
    protected $attrs = [];
    protected $cnt = 0;


    /**
     * @param Assertion $assertion
     *
     * @return static
     */
    public static function fromAssertion(Assertion $assertion)
    {
        $attributes = $assertion->getFirstAttributeStatement()->getAllAttributes();

        $me = new static;

        foreach($attributes as $attribute)
        {
            /** @var $attribute Attribute */
            $me->add($attribute);
        }

        $me->setNameId($assertion->getSubject()->getNameID());

        return $me;
    }


    /**
     * @param NameID $name_id
     */
    public function setNameId(NameID $name_id)
    {
        $this->name_id = $name_id;
    }


    /**
     * @return NameID
     */
    public function getNameId()
    {
        return $this->name_id;
    }


    /**
     * @return string
     */
    public function getNameIdValue()
    {
        return $this->getNameId()->getValue();
    }


    /**
     * @return null|string
     */
    public function getNameIdFormat()
    {
        return $this->getNameId()->getFormat();
    }


    /**
     * @param $attr
     *
     * @return bool
     */
    public function has($attr)
    {
        return isset($this->index[$attr]);
    }


    /**
     * @param      $attr
     * @param null $default
     *
     * @return Attribute|null
     */
    public function get($attr, $default = null)
    {
        if(!$this->has($attr))
        {
            return $default;
        }

        return $this->attrs[$this->index[$attr]];
    }


    /**
     * @param Attribute $attr
     *
     * @return $this
     */
    public function add(Attribute $attr)
    {
        $idx = $this->cnt;

        $this->attrs[$idx] = $attr;

        $this->index[$attr->getName()] = $idx;

        $this->cnt++;

        return $this;
    }


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


    /**
     * @param bool|false $all
     *
     * @return array
     */
    public function toArray($all = false)
    {
        $result = [];

        foreach($this->attrs as $attr)
        {
            /** @var $attr Attribute */

            $result[$attr->getName()] = $all ? $attr->getAllAttributeValues() : $attr->getFirstAttributeValue();
        }

        return $result;
    }
}