<?php

namespace App\Command;

use App\Entity\Filial;
use App\Entity\Department;
use App\Entity\Specialist;
use App\Entity\Location;
use App\Entity\Idoctor;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\DependencyInjection\ContainerInterface;

class UploadDoctorsOnlineCommand extends Command
{
    protected static $defaultName = 'upload:doctorsOnline';
    protected static $defaultDescription = 'Обновление и загрузка онлайн врачей';
    protected $entityManager = null;
    protected $io = null;

    public function __construct(ContainerInterface $container)
    {
        parent::__construct();
        $this->entityManager = $container->get('doctrine')->getManager();
    }

    protected function configure(): void
    {
        $this->setDescription(self::$defaultDescription);
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->io = new SymfonyStyle($input, $output);

        $doctorsOnline = $this->entityManager
            ->getRepository(Idoctor::class)
            ->findBy(['onlineMode' => 1]);

        foreach ($doctorsOnline as $doctor) {
            $specialist = $this->entityManager->getRepository(Specialist::class)
                ->findByDcode($doctor->getDcode());

            if ($specialist) {
                $locationEntity = $this->entityManager->getRepository(Location::class)
                    ->findOneBy([
                    'dcode' => $doctor->getDcode(),
                    'department' => $doctor->getDepartmentId(),
                    'filial' => $doctor->getFilialId(),
                    'onlineMode' => $doctor->getOnlineMode()
                ]);

                $filial = $this->entityManager->getRepository(Filial::class)
                    ->findOneBy(['fid' => $doctor->getFilialId()]);
                $department = $this->entityManager->getRepository(Department::class)
                    ->findOneBy(['did' => $doctor->getDepartmentId()]);

                if (is_null($locationEntity)) {
                    $locationEntity = new Location();
                }

                $locationEntity
                    ->setDcode($doctor->getDcode())
                    ->setDepartment($department)
                    ->setFilial($filial)
                    ->setSpecialist($specialist)
                    ->setOnlineMode($doctor->getOnlineMode())
                    ->setActive(1)
                ;

                $this->entityManager->persist($locationEntity);
            }
        }

        $this->entityManager->flush();

        return Command::SUCCESS;
    }
}
