<?php

namespace Shop\Services;

use Aura\Auth\Status;
use Core\Concrete\AuthFactory;
use Project\Models\Person\PersonQuery;
use Project\Models\Person\Person;
use Symfony\Component\HttpFoundation\Request;

/**
 * Description of Auth
 *
 * @author Dmitriy
 */
class Auth extends \Diamond\Services\Auth
{

    const PERSON_KEY = 'customer_id';

    protected $personCache = [];

    public function __construct(
        AuthFactory $authFactory,
        \Diamond\Config\Main $mainConf
    )
    {
        parent::__construct($authFactory, $mainConf);
    }


    public function authCustomer($login, $password, $remeber = false)
    {

        if (!$User = \Shop\Models\Customer\CustomerQuery::create()
            ->filterByEmail($login)
            ->filterByPassword($password)
            ->findOne()) {
            return false;
        }

        $userdata = array(
            'customer_name' => $User->getName(),
            self::PERSON_KEY => $User->getId(),
            'customer_email' => $User->getEmail()
        );

        $userName = md5(serialize($userdata));

        //авторизующий серсис
        $loginService = $this->authFactory->newLoginService();

        //объект авторизации
        $authService = $this->authFactory->newInstance();
        if ($authService->isAnon() || $authService->getUserName() !== $userName) {

            $loginService->forceLogin($authService, $userName, $userdata);
        }

        $User
            ->setLastAuth(time())
            ->save();

        return true;
    }


    /**
     * Get Auth Person
     * @return boolean|Shop\Models\Customer\Customer
     */
    public function getAuthCustomer()
    {
        $auth = $this->getAuth();

        if ($auth) {

            $userdata = $auth->getUserData();

            if (isset($userdata[self::PERSON_KEY])) {

                return $this->getPerson($userdata[self::PERSON_KEY]);

            }

        }

        return false;
    }

    /**
     *
     * @param type $key
     * @return boolean
     */
    protected function getPerson($key)
    {
//        dump($this->personCache);
        if (isset($this->personCache[$key])) {
            return $this->personCache[$key];
        }
        $person = \Shop\Models\Customer\CustomerQuery::create()->setComment("test")->findOneById($key);

        $this->personCache[$key] = $person;

        if (!$person) {
            return false;
        }

        return $person;
    }

    /**
     * @param string $pass
     * @return bool
     */
    public function fastAuthByPass(string $pass):bool
    {

        $customer = \Shop\Models\Customer\CustomerQuery::create()
            ->filterByPassword($pass)
            ->findOne()
        ;
        if($customer){
            return $this->authCustomer($customer->getEmail(), $customer->getPassword());
        }

        return false;
    }
}
