<?php

declare(strict_types=1);

/*
 * This file is part of vonRotenberg Shopware API Bundle.
 *
 * (c) vonRotenberg
 *
 * @license proprietary
 */

namespace vonRotenberg\ShopwareApiBundle\Command;

use Contao\CoreBundle\Framework\ContaoFramework;
use Contao\System;
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\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use vonRotenberg\ShopwareApiBundle\API\Shopware;

class ShopwareGetProductsBySku extends Command
{
    protected static $defaultName = 'shopware:get-products-by-sku';

    protected $framework;

    public function __construct(ContaoFramework $framework)
    {
        $this->framework = $framework;

        parent::__construct();
    }

    protected function configure(): void
    {
        $this
            ->setName(self::$defaultName)
            ->setDescription('Search Shopware products by SKU')
            ->addOption('short','s',InputOption::VALUE_NONE, 'Short result: Only show name and basic product infos')
        ;
    }
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->framework->initialize();
        $cloner = new VarCloner();
        $dumper = new CliDumper();

        $io = new SymfonyStyle($input, $output);
        $io->title('Shopware products search by SKU');
        $strSku = $io->ask('Enter SKU to search for');

        /** @var Shopware $Shopware */
        $Shopware = System::getContainer()->get(Shopware::class);

        $Result = $Shopware->getProductsForSku($strSku,true, $input->getOption('short') ? true : false);

        if ($Result->getStatusCode() === 200)
        {
            $Content = json_validate($Result->getContent()) ? json_decode($Result->getContent(), true) : $Result;

            if ($Content['total'])
            {
                $dumper->dump(($cloner->cloneVar($Content['data'])));
            }
            $io->success(sprintf('Found %s product(s)',$Content['total']));

            return self::SUCCESS;
        }
        $io->error(sprintf('Could not retrieve products by SKU. HTTP Status returned: %s',$Result->getStatusCode()));

        return self::FAILURE;
    }
}