<?php

namespace App\Command\Migration;

use App\Entity\Client;
use App\Entity\HardwareProfile;
use App\Entity\OrganizationalUnit;
use App\Model\OrganizationalUnitTypes;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

#[AsCommand(name: 'opengnsys:migration:clients', description: 'Migrate clients data')]
class MigrateClientsCommand extends Command
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly ManagerRegistry $doctrine
    )
    {
        parent::__construct();
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        /** @var EntityManagerInterface $oldDatabaseEntityManager */
        $oldDatabaseEntityManager = $this->doctrine->getManager('og_1');

        $clientRepository = $this->entityManager->getRepository(Client::class);
        $organizationalUnitRepository = $this->entityManager->getRepository(OrganizationalUnit::class);
        $hardwareProfileRepository = $this->entityManager->getRepository(HardwareProfile::class);

        /** Obtener los ordenadores de la base de datos antigua **/
        $rsmClients = new ResultSetMapping();
        $rsmClients->addScalarResult('idordenador', 'idordenador');
        $rsmClients->addScalarResult('nombreordenador', 'nombreordenador');
        $rsmClients->addScalarResult('numserie', 'numserie');
        $rsmClients->addScalarResult('mac', 'mac');
        $rsmClients->addScalarResult('ip', 'ip');
        $rsmClients->addScalarResult('netiface', 'netiface');
        $rsmClients->addScalarResult('netdriver', 'netdriver');
        $rsmClients->addScalarResult('idperfilhard', 'ordenadores.idperfilhard');
        $rsmClients->addScalarResult('grupoid', 'ordenadores.grupoid');
        $rsmClients->addScalarResult('idaula', 'ordenadores.idaula');

        $clientsQuery = $oldDatabaseEntityManager->createNativeQuery('SELECT idordenador, nombreordenador, numserie, ip,  mac, netiface, netdriver, ordenadores.idaula, ordenadores.grupoid, ordenadores.idperfilhard FROM ordenadores LEFT JOIN aulas ON ordenadores.idaula = aulas.idaula LEFT JOIN perfileshard ON ordenadores.idperfilhard = perfileshard.idperfilhard', $rsmClients);
        $clients = $clientsQuery->getResult();

        /** Ordenadores **/
        $output->writeln("CLIENTES TOTAL: ". count($clients));
        foreach ($clients as $client){
            $clientEntity = $clientRepository->findOneBy(['migrationId' => $client['idordenador']]);
            if(!$clientEntity){
                $clientEntity = new Client();
                $clientEntity->setMigrationId($client['idordenador']);
                $clientEntity->setName($client['nombreordenador']);
                $clientEntity->setSerialNumber($client['numserie']);
                $clientEntity->setNetiface($client['netiface']);
                $clientEntity->setNetdriver($client['netdriver']);
                $clientEntity->setMac($client['mac']);
                $clientEntity->setIp($client['ip']);
                $clientEntity->setMaintenance(false);
                $clientEntity->setPosition(['x' => 0, 'y' => 0]);
            }

            $migrationId = match ($client['ordenadores.grupoid']) {
                0 => OrganizationalUnitTypes::CLASSROOM . '-' . $client['ordenadores.idaula'],
                default => OrganizationalUnitTypes::CLIENTS_GROUP . '-' . $client['ordenadores.grupoid'],
            };
            $organizationalUnit = $organizationalUnitRepository->findOneBy(['migrationId' => $migrationId]);

            if (!$organizationalUnit){
                $output->writeln("ORGANIZATIONAL UNIT NOT FOUND: ". $migrationId);
            }

            if ($organizationalUnit){
                $clientEntity->setOrganizationalUnit($organizationalUnit);
            }

            $hardwareProfile = $hardwareProfileRepository->findOneBy(['migrationId' => $client['ordenadores.idperfilhard']]);
            if ($hardwareProfile){
                $clientEntity->setHardwareProfile($hardwareProfile);
            }

            $this->entityManager->persist($clientEntity);
        }
        $this->entityManager->flush();

        return Command::SUCCESS;
    }

}