<?php

namespace Actigraph\ActipageBaseBundle\Services\Account;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;

class LocalAccount
{
    private $type;
    private $accountManager;

    private $em;
    private $error;

    private $session;

    public function __construct(EntityManagerInterface $em, SessionInterface $session, $params)
    {
        $this->type = 'form';
        $this->em = $em;
        $this->error = null;
        $this->session = $session;
        $this->accountManager = isset($params['account']['manager']) ? $params['account']['manager'] : null;
    }

    public function getType()
    {
        return $this->type;
    }

    public function checkLogin(array $data)
    {
        if (isset($data['email']) && $data['email'] != null && $data['email'] != '') {
            $email = $data['email'];
        } else {
            $this->error = 'Veuillez remplir votre mail.';

            return false;
        }
        if (isset($data['password']) && $data['password'] != null && $data['password'] != '') {
            $password = $data['password'];
        } else {
            $this->error = 'Veuillez remplir votre mot de passe.';

            return false;
        }
        if ($this->accountManager === 'local_tadao') {
            $user = $this->em->getRepository(\App\Entity\LocalAccount::class)->findOneBy(['email' => $email, 'isEnable' => true]);
            if ($user == null || !password_verify($password, $user->getPassword())) {
                $this->error = 'L\'adresse email ou le mot de passe est incorrect.';
                return false;
            }

            return $user;
        }

        $hash = hash('sha512', $password);
        $user = $this->em->getRepository(\App\Entity\LocalAccount::class)->findOneBy(['email' => $email, 'password' => $hash, 'isEnable' => true]);

        if ($user == null) {
            $this->error = 'L\'adresse email ou le mot de passe est incorrect.';
            return false;
        }

        return $user;
    }

    public function getError()
    {
        return $this->error;
    }

    public function login($user)
    {
        $this->session->set('accountId', $user->getId());
        $user->setLastLoginAt(new \DateTime());

        $this->em->flush();

        return true;
    }

    public function getUser()
    {
        if ($this->session->get('accountId') == null) {
            return false;
        }

        return $this->em->getRepository(\App\Entity\LocalAccount::class)->find($this->session->get('accountId'));
    }

    public function logout()
    {
        $this->session->set('accountId', null);
        $this->session->remove('loginReferer');

        return true;
    }
}
