<?php

namespace App\Command;

use App\Entity\Department;
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;
use Symfony\Contracts\HttpClient\HttpClientInterface;


class UploadDepInfoclinicaCommand extends Command
{
    private $container;
    private $client;

    public function __construct(ContainerInterface $container, HttpClientInterface $client)
    {
        parent::__construct();
        $this->container = $container;
        $this->client = $client;
    }

    protected static $defaultName = 'app:UploadDep';
    protected static $defaultDescription = 'Обновление отделений для врачей';

    protected function configure(): void
    {
        $this
            ->setDescription(self::$defaultDescription)
            ->addArgument('var', InputArgument::OPTIONAL, 'variant update table')
            ->addOption('option1', null, InputOption::VALUE_NONE, 'Option description')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $entityManager = $this->container->get('doctrine')->getManager();
        $io = new SymfonyStyle($input, $output);

        $response = $this->client->request('GET', '/specialists/departments', [
            'verify_peer' => false,
            'verify_host' => false,
            'base_uri' => 'https://widget.sovamed.ru',
            'headers' => [
                'Content-Type' => 'application/json',
                'User-Agent' => 'sovamed_bot'
            ],
        ]);
        
        $response = $response->toArray();

        foreach ($response['data'] as $item) {
            $department = $entityManager->getRepository(Department::class)
                ->findOneBy([
                    'did' => $item['id']
                ]);
        
            if (is_null($department)) {
                $department = new Department();    
            }
            
            if (empty($item['viewInWeb'])) {
                $item['viewInWeb'] = 0;
            }
            
            $department
                ->setDid($item['id'])
                ->setName($item['name'])
                ->setAlias('')
                ->setGroupName($item['groupName'])
                ->setActive($item['viewInWeb'])
                ->setOnlineMode($item['onlineMode'])
            ;
            
            $entityManager->persist($department);
            $entityManager->flush();
            
            $io->success('load: '. $department->getId());
        }

        return Command::SUCCESS;
    }
}
