<?php

namespace App\Command;

use App\Entity\PriceDepartment;
use App\Entity\PriceList;
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 UploadPriceInfoclinicaCommand 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:UploadPice';
    protected static $defaultDescription = 'Обновление цен';

    protected function configure(): void
    {
        $this
            ->setDescription(self::$defaultDescription)
            ->addArgument('did', InputArgument::OPTIONAL, 'department id update')
            ->addOption('debug', null, InputOption::VALUE_NONE, 'debug on')
            ->addOption('nosleep', null, InputOption::VALUE_OPTIONAL, 'sleep true|false default false')
        ;
    }

    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $entityManager = $this->container->get('doctrine')->getManager();
        $io = new SymfonyStyle($input, $output);
        $departments = $entityManager->getRepository(PriceDepartment::class)->findAll();
        $departmentId = $input->getArgument('did');
        $debug = $input->getOption('debug');
        $nosleep = $input->getOption('nosleep');
        
        if ($departmentId) {
            $departments = $entityManager->getRepository(PriceDepartment::class)
                ->findBy(['groupId' => $departmentId]);
        }

        if (empty($departments))
            return Command::FAILURE;
        
        foreach ($departments as $department) {
            foreach ($this->getPricelist($department->getGroupId()) as $collection) {
                foreach ($collection as $item) {
                    $priceList = $entityManager->getRepository(PriceList::class)
                        ->findOneBy([
                            'kodoper' => $item['kodoper'],
                            'speccode' => $item['speccode'],
                            'filial' => $item['filial'],
                            'groupId' => $department->getGroupId()
                        ]);   
                
                    $text = 'update: ';

                    if (is_null($priceList)) {
                        $priceList = new priceList();    
                        $text = 'create: ';
                    }

                    $priceList
                        ->setKodoper($item['kodoper'])
                        ->setSchname($item['schname'])
                        ->setSpecname($item['specname'])
                        ->setSpeccode($item['speccode'])
                        ->setPriceInfo($item['priceInfo'])
                        ->setDiscpercent($item['discpercent'])
                        ->setDiscprice($item['discprice'])
                        ->setStructname($item['structname'])
                        ->setFname($item['fname'])
                        ->setFilial($item['filial'])
                        ->setComment($item['comment'])
                        ->setMediaId($item['mediaId'])
                        ->setDateUpdate(new \DateTime())
                        ->setGroupId($department->getGroupId());

                    $entityManager->persist($priceList);
                    $entityManager->flush(); 

                    if ($debug)
                        $io->success($text. $priceList->getId());
                }
            }

            if ($debug)
                $io->info('sleep: 2 sec');
            
            if (empty($nosleep)) 
                sleep(2);
        }

        $io->success('successful');
        
        return Command::SUCCESS;
    }

    private function getPricelist($depnum)
    {
        $response = [];
        $flag = true;
        $firstrow = 1;
        $lastrow = 500;
        
        while ($flag) {
            $result = $this->client->request('GET', 'pricelist/list', [
                'verify_peer' => false,
                'verify_host' => false,
                'base_uri' => 'https://widget.sovamed.ru',
                'headers' => [
                    'Content-Type' => 'application/json',
                    'User-Agent' => 'sovamed_bot'
                ],
                'query' => [
                    'depnum' => $depnum,
                    'firstrow' => $firstrow,
                    'lastrow' => $lastrow
                ],
            ]);

            $firstrow = $lastrow + 1; 
            $lastrow = $lastrow + 500; 
            $result = $result->toArray();
            
            if (empty($result['data'])) {
                $flag = false;
            } else {
                $response[] = $result['data'];
            }

            if (empty($nosleep))
                sleep(3);
        }

        return $response;
    }
}
