<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\EditProfileFormType;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Sunrise\Slugger\Slugger;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Validator\ValidatorInterface;

/**
 * Class UserController.
 */
class UserController extends BaseController
{

    #[Route(path: '/profile/edit/{username}', name: 'app_profile_edit')]
    public function editProfile(Request $request, UserRepository $userRepository, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $entityManager, string $username = ''): Response
    {
        if ($username !== '') {
            if ($this->isGranted(attribute: 'ROLE_ADMIN')) {
                $user = $userRepository->findOneBy([
                    'username' => $username,
                ]);
            } else {
                throw new AccessDeniedException(message: 'Only admins are allowed to edit foreign profiles.');
            }
        } else {
            $user = $this->getUser();
        }

        $form = $this->createForm(type: EditProfileFormType::class, data: $user);
        $form->handleRequest(request: $request);

        if ($form->isSubmitted() && $form->isValid()) {
            $user = $form->getData();
            // if there's a new password, use it

            if ($form->get(name: 'newPassword')->getData())
                $user->setPassword(
                    password: $userPasswordHasher->hashPassword(
                        user: $user,
                        plainPassword: $form->get(name: 'newPassword')->getData()
                    )
                );

            $entityManager->persist(entity: $user);
            $entityManager->flush();

            return $this->redirectToRoute(route: 'app_main');
        };

        return $this->renderForm(view: '@default/user/edit_profile.html.twig', parameters: [
            'user' => $user,
            'userForm' => $form
        ]);
    }


    #[Route(path: '/profile/{username}', name: 'app_profile')]
    public function showProfile(UserRepository $userRepository, string $username = ''): Response
    {
        /* var User $user */
        if ($username === '') {
            $user = $this->getUser();
        } else {
            $user = $userRepository->findOneBy([
                'username' => $username,
            ]);
        }

        return $this->render(view: '@default/user/show_profile.html.twig', parameters: [
            'user' => $user,
        ]);
    }

    #[Route(path: '/list_users/', name: 'app_list_user')]
    public function listUsers(UserRepository $userRepository): Response
    {
        $users = $userRepository->findAll();

        return $this->render(view: '@default/user/list_users.html.twig', parameters: [
            'users' => $users,
        ]);
    }

    // TODO move to a helper class
    function humanFilesize($bytes, $decimals = 2)
    {
        $sz = 'BKMGTP';
        $factor = floor((strlen($bytes) - 1) / 3);
        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
    }


    #[Route(path: '/user/upload/avatar/{id}', name: 'user_upload_avatar')]
    public function uploadAvatar(
        Request                $request,
        UserRepository         $userRepository,
        EntityManagerInterface $entityManager,
        ValidatorInterface     $validator,
        int                    $id)
    {
        $user = $userRepository->find($id);

        if (!$user) {
            return $this->json('User not found.', 404);
        }

        $postMaxSize = UploadedFile::getMaxFilesize();
        $contentLength = $request->headers->get('Content-length');

        if ($contentLength > $postMaxSize) {
            return $this->json('File is bigger than the allowed ' . $this->humanFilesize($postMaxSize) . ' Bytes.', 400);
        }

        $uploadedAvatar = $request->files->get('file');
        $destination = $this->getParameter(name: 'kernel.project_dir') . '/public/uploads/avatars';
        $originalFilename = pathinfo($uploadedAvatar->getClientOriginalName(), PATHINFO_FILENAME);
        $slugger = new Slugger();
        $cleanFilename = $slugger->slugify($originalFilename);
        $newFilename = $cleanFilename . '-' . uniqid() . '.' . $uploadedAvatar->guessExtension();
        $uploadedAvatar->move($destination, $newFilename);
        $user->setAvatar($newFilename);
        $entityManager->persist(entity: $user);
        $entityManager->flush();

        return $this->json(data: 'OK', status: 201);
    }
}
