<?php

namespace App\Command;

use App\Entity\PriceDepartment;
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 UploadPriceDepInfoclinicaCommand 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:UploadPiceDep';
    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', '/pricelist/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(PriceDepartment::class)
                ->findOneBy([
                    'groupId' => $item['id']
                ]);
        
            if (is_null($department)) {
                $department = new PriceDepartment();    
            }
            
            if (empty($item['viewInWeb'])) {
                $item['viewInWeb'] = 0;
            }
            
            $department
                ->setGroupId($item['id'])
                ->setName($item['name'])
                ->setGroupName($item['groupName'])
                ->setViewInWeb($item['viewInWeb'])
                ->setDoctCount($item['schCount'])
            ;
            
            $entityManager->persist($department);
            $entityManager->flush();
            
            $io->success('load: '. $department->getId());
        }

        return Command::SUCCESS;
    }
}
