<?php

namespace Webkul\DamBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Console\Input\InputOption;

class ExpiredCommand extends ContainerAwareCommand
{
    /** @var EntityManager */
    protected $em;

    public function __construct(
        $em
    ) {
        $this->em = $em;
        parent::__construct();
    }

    protected function configure()
    {
        parent::configure();

        $this->setName('dam:asset:check-expire')
             ->setDescription('Check Expired Dam Module')
             ->addOption('force', 'f', InputOption::VALUE_NONE, 'Force deletion');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $removeAssetCount = 0;
        $io->title("Check Expired Dam Module");
        $force = $input->getOption('force');

        if (!$force) {
            $io->note('Command running in safe mode. Use --force to delete assets.');
        }

        $io->writeln('Searching assets...');
        $assets = $this->getContainer()->get('webkul_dam.repository.asset')->findAll();
        $output->writeln(sprintf('Found %d Assets', count($assets)));
        
        $removed = 0;
        foreach ($assets as $asset) {
            $defaultTimeZone = $asset->getDefaultTimezone() ? : 'UTC';
            date_default_timezone_set($defaultTimeZone);
            $currentDate = date("Y-m-d");
            $dateToBeExpired = $asset->getExpirationDate() ? : null;
            
            if ($dateToBeExpired) {
                if (strtotime($currentDate) >= strtotime($dateToBeExpired)) {
                    if ($force) {
                        foreach ($asset->getMedias() as $media) {
                            $this->em->remove($media);
                        }
                        $this->em->remove($asset);
                        $this->em->flush();
                        $removed++;
                    }
                    $removeAssetCount++;
                }
            }
        }

        $io->writeln(sprintf('Found %d Expired Asset, Removed %s', $removeAssetCount, $removed));
        $io->success("Checked all expired Assets.");
    }
}
