<?php

/*
 * This file is part of the SncRedisBundle package.
 *
 * (c) Henrik Westphal <henrik.westphal@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */
namespace OfficeBrain\Bundle\CoreBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

use OfficeBrain\Bundle\CoreBundle\Cache\RedisCacheService;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Input\InputOption;

/**
 * Symfony command to execute redis flushdb
 *
 * @author Sebastian Göttschkes <sebastian.goettschkes@googlemail.com>
 */
class RedisFlushKeyWithPrefixCommand extends ContainerAwareCommand
{
	
    /**
     * {@inheritDoc}
     */
    protected function configure()
    {
        parent::configure();

        $this->setName('redis:flushkey')
            ->setDescription('Flushes the redis database using the redis flushdb command')
            ->addOption('prefix', null, InputOption::VALUE_REQUIRED, 'Key prefix')
            ->addOption('client', null, InputOption::VALUE_REQUIRED, 'Redis client');
    }

    /**
     * {@inheritdoc}
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
    	$keyprifix = $input->getOption('prefix');
    	$client = $input->getOption('client');
        if (isset($keyprifix)) {
            $this->flushKeyForClient($keyprifix,$client,$output);
        } else {
            $this->output->writeln('<error>Flushing cancelled</error>');
        }
    }

    /**
     * Getting the client from cmd option and flush's the db
     */
    private function flushKeyForClient($cachePrefix,$client="default",$output)
    {
    	if(!RedisCacheService::isCacheEnable())
    	{
    		return null;
    	}
    	$cacheClient=RedisCacheService::create($cachePrefix,$client);
    	RedisCacheService::removeCacheWithPrifix($cacheClient,$cachePrefix);

        $output->writeln('<info>'.$client.' client flushed for prefix '.$cachePrefix.' </info>');
    }

}

