<?php

namespace App\Controller;

use App\Entity\Note;
use App\Entity\User;
use App\Entity\Speaker;
use App\Entity\Series;
use App\Entity\SharedNote;
use App\Service\DatabaseTransferService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class DefaultController extends AbstractController
{
    #[Route('/', name: 'app_index')]
    public function index(): Response
    {
        if ($this->isGranted('IS_AUTHENTICATED_FULLY')) {
            return $this->redirect('/home');
        }
        return $this->render('default/index.html.twig', ['onLoad' => null]);
    }

    #[Route('/home', name: 'app_home')]
    public function home(Request $req, EntityManagerInterface $emi, #[CurrentUser()] ?User $user): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        $last4Notes = $emi->getRepository(Note::class)->getLast4Notes($user);
        $openNotes = $emi->getRepository(Note::class)->reverseNoteSort($user);
        $meta = $user->getMetaData();
        $speakers = $emi->getRepository(Speaker::class)->findBy(['user' => $user], ['name' => 'ASC']);
        $series = $emi->getRepository(Series::class)->findBy(['user' => $user], ['name' => 'ASC']);

        return $this->render('default/home.html.twig', [
            //'onLoad' => 'initHome()',
            'last4Notes' => $last4Notes,
            'reverseNoteSort' => $openNotes,
            'isAdmin' => $this->isGranted('ROLE_ADMIN'),
            'xferDB' => DatabaseTransferService::isTransferEnabled(),
            'meta' => $meta,
            'speakers' => $speakers,
            'series' => $series,
        ]);
    }

    #[Route('/cheat-sheet', name: 'app_cheat_sheet')]
    public function cheatSheet(): Response
    {
        return $this->render('default/cheat-sheet.html.twig');
    }

    #[Route('/profile', name: 'app_profile')]
    public function profile(EntityManagerInterface $emi): Response
    {
        /** @var User $user */
        $user = $this->getUser();
        if (!$user) {
            return $this->redirectToRoute('app_login');
        }
        $meta = $user->getMetaData();
        if (!$meta) {
            $meta = [
                'onLoad' => null,
                'saveInterval' => 15,
                'saveReferences' => 'checked',
                'noteTextSize' => 12,
                'trackSaveSize' => null,
                'saveFailureCount' => 3,
                'saveTimeout' => 5,
            ];
        } else {
            $meta['saveReferences'] = $meta['saveReferences'] ? 'checked' : null;
            $meta['trackSaveSize'] = $meta['trackSaveSize'] ? 'checked' : null;
        }

        $sharedWithMe = $emi->getRepository(SharedNote::class)->getNotesSharedWithMe($user);
        $shared = $emi->getRepository(SharedNote::class)->getNotesSharedByMe($user);
        //dump($shared);

        return $this->render('default/profile.html.twig', [
            'onLoad' => 'rollUp("user");rollUp("settings")',
            'meta' => $meta,
            'sharedWithMe' => $sharedWithMe,
            'shared' => $shared,
            'user' => $this->getUser(),
        ]);
    }

    #[Route('/reference-editor', 'app_reference_editor')]
    public function referenceEditor(EntityManagerInterface $emi): Response
    {
        $this->denyAccessUnlessGranted('ROLE_ADMIN');

        return $this->render('editors/reference-editor.html.twig');
    }

    #[Route('/template-editor', 'app_template_editor')]
    public function templateEditor(): Response
    {
        $this->denyAccessUnlessGranted('IS_AUTHENTICATED_FULLY');
        return $this->render('editors/template-editor.html.twig');
    }

    #[Route('/xfer-database', name: 'app_admin_transfer_db')]
    public function transfer(DatabaseTransferService $service, Request $request): Response
    {
        $step = $request->query->get('step', 'init');
        $session = $request->getSession();

        if ($step === 'init') {
            $service->createSchema();
            $session->remove('transfer_logs');
            return $this->redirectToRoute('app_admin_transfer_db', ['step' => 0]);
        }

        if ($step === 'summary') {
            // Finalize
            $service->finalizeEnvSwap();
            
            return $this->render('default/transfer_summary.html.twig', [
                'logs' => $session->get('transfer_logs', [])
            ]);
        }

        $classes = $service->getEntityClasses();
        $totalClasses = count($classes);

        if (isset($classes[$step])) {
            $class = explode("\\", $classes[$step]);
            $className = end($class);

            $func = "transfer{$className}Table";

            if (method_exists($service, $func)) {
                $skippedCount = $service->{$func}();

                if ($skippedCount > 0) {
                    $logs = $session->get('transfer_logs', []);
                    $logs[] = "Skipped $skippedCount orphaned records in the $className table.";
                    $session->set('transfer_logs', $logs);
                }

                $progress = round((($step+1) / $totalClasses) * 100);
                $nextStep = (($step + 1) < $totalClasses) ? ($step + 1) : 'summary';
                $var = explode("\\", $classes[$step+1]);

                return $this->render('default/transfer_progress.html.twig', [
                    'current' => (isset($classes[$step+1]) ? end($var) : 'summary'),
                    'progress' => $progress,
                    'next_step' => $nextStep,
                ]);
            }
        }

        // Step 7: Logout and redirect
        return $this->redirectToRoute('app_logout'); 
    }
}
