<?php

namespace AuthStack\AuthProfile;

use Illuminate\Support\Collection;
use AuthStack\AuthProfile\Model\AuthProfile;
use AuthStack\AuthProfile\Errors\NoActiveProfileError;

class ProfileManager
{
    protected $collection;
    protected $active_profile;


    /**
     * @param array $data
     * @param       $active_profile
     *
     * @return ProfileManager
     */
    public static function fromArray(array $data, $active_profile)
    {
        $me = new static;

        $me->collection = collect($data);

        return $me->setActiveProfile($active_profile);
    }


    /**
     * @return Collection
     */
    public function getCollection()
    {
        return $this->collection;
    }


    /**
     * @param string $session_id
     *
     * @return $this
     */
    public function setActiveProfile($session_id = '')
    {
        $this->active_profile = $session_id;

        return $this;
    }


    /**
     * @return AuthProfile
     * @throws NoActiveProfileError
     */
    public function getActiveProfile()
    {
        $result = $this->getCollection()->where('session_id', $this->active_profile);

        if(!$result->count())
        {
            throw new NoActiveProfileError("The profile collection did not contain an active profile specified in the session.");
        }

        return AuthProfile::fromArray($result->first());
    }
}