<?php
/**
 * @author Ulrich Hecht <ulrich.hecht@hecht-software.de>
 * @date 03/24/2017
 */

namespace AppBundle\Command;

use AppBundle\Entity\SunstarTravelProgram;
use AppBundle\Util;
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

class SunstarImportCommand extends ContainerAwareCommand
{
    protected function configure()
    {
        $this->setName('sterntours:import-sunstar');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        /** @var \Doctrine\ORM\EntityManager $em */
        $em = $this->getContainer()->get('doctrine')->getManager();
        $conn = $em->getConnection();

        $r = Util::httpGet('https://www.jugendreisen-spezialist.de/sterntours-export/index.php', [
            'Authorization: Basic c3Rlcm50b3VyczpvbW1DVm5OY2lXTDRSMUhw'
        ]);
        $tpDataEntries = json_decode($r['content'], true);
        $conn->beginTransaction();
        try
        {
            $metadata = $em->getClassMetaData('AppBundle:SunstarTravelProgram');
            $metadata->setIdGeneratorType(\Doctrine\ORM\Mapping\ClassMetadata::GENERATOR_TYPE_NONE);
            $metadata->setIdGenerator(new \Doctrine\ORM\Id\AssignedGenerator());

            $conn->query('SET FOREIGN_KEY_CHECKS=0');
            $conn->query('DELETE FROM '. $metadata->getTableName());
            $conn->query('SET FOREIGN_KEY_CHECKS=1');
            $i = 0;
            foreach ($tpDataEntries as $tpData)
            {
                ++$i;
                $sunTp = new SunstarTravelProgram();
                $sunTp->setId($i);
                $sunTp->setTitle($tpData['title']);
                $sunTp->setDescription($tpData['description']);
                $sunTp->setDestination($tpData['destination_name']);
                $sunTp->setUrl($tpData['url']);
                $sunTp->setImageUrl('https://www.jugendreisen-spezialist.de'. $tpData['image_url']);
                $sunTp->setDuration($tpData['duration']);
                $sunTp->setMinimumPrice($tpData['minimum_price']);
                $sunTp->setMinimumAge($tpData['minimum_age']);
                $sunTp->setMaximumAge($tpData['maximum_age']);

                $em->persist($sunTp);
                $em->flush();
            }
            $conn->commit();
        }
        catch (\Exception $e)
        {
            $conn->rollBack();
            throw $e;
        }
    }
}