<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele Termini
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\Model\Manager;

use ActiveRecord\QueryOptions;
use Application\Admin\Model\ArchiveLastView;
use Application\Core\Entity\AccountInterface;

class ArchiveLastViewManager
{
    /**
     * @var array
     */
    protected $identities = [];

    /**
     * @param int|AccountInterface $account
     * @param                      $entity_type
     * @return ArchiveLastView
     */
    public function findByEntity($account, $entity_type)
    {
        if ($account instanceof AccountInterface) {
            $user_id = $account->getId();
        } elseif (is_numeric($account)) {
            $user_id = intval($account);
        } else {
            throw new \InvalidArgumentException('Integer or instance of AccountInterface expected');
        }

        if (!isset($this->identities[$entity_type][$user_id])) {
            $qo = new QueryOptions();
            $qo->addCondition(['entity_type = :et', 'et' => $entity_type]);
            $qo->addCondition(['user_id = :user', 'user' => $user_id]);

            $this->identities[$entity_type][$user_id] = ArchiveLastView::first($qo->getOptions());
        }

        return $this->identities[$entity_type][$user_id];
    }

    public function save(ArchiveLastView $archive_last_view)
    {
        $archive_last_view->save();
    }
}
