<?php
namespace Backend\BaseBundle\Command;

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Backend\BaseBundle\Model;

class CreateSiteCommand extends ContainerAwareCommand
{
    /**
     * @see Command
     */
    protected function configure()
    {
        $this
            ->setName('dgfactor:site:create')
            ->setDescription('建立站台')
            ->setDefinition(array(
                new InputArgument('slug', InputArgument::REQUIRED, '站台代碼'),
                new InputArgument('functions', InputArgument::REQUIRED, '啟用模組(使用,分隔)'),
            ))
            ->setHelp(<<<EOT
The <info>dgfactor:site:create</info> 建立站台後台登入帳號:

  <info>php app/console dgfactor:site:create dgfactor</info>
EOT
            );
    }

    /**
     * @see Command
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $slug   = $input->getArgument('slug');
        $functions   = $input->getArgument('functions');
        $enabledFunctions = explode(',', $functions);
        $site = new Model\Site();
        $site->setSlug($slug);
        $site->setEnabled(true);
        $site->setEnabledFunctions($enabledFunctions);
        $site->save();
        $output->writeln(sprintf('Created site <comment>%s</comment>', $slug));
    }

    /**
     * @see Command
     */
    protected function interact(InputInterface $input, OutputInterface $output)
    {
        if (!$input->getArgument('slug')) {
            $slug = $this->getHelper('dialog')->askAndValidate(
                $output,
                '站台代碼:',
                function($slug) {
                    if (empty($slug)) {
                        throw new \Exception('站台代碼不能為空');
                    }

                    return $slug;
                }
            );
            $input->setArgument('slug', $slug);
        }

        if (!$input->getArgument('functions')) {
            $functions = $this->getHelper('dialog')->askAndValidate(
                $output,
                '啟用功能(用,分隔):',
                function($functions) {
                    if (empty($functions)) {
                        throw new \Exception('啟用模組不能為空');
                    }

                    return $functions;
                }
            );
            $input->setArgument('functions', $functions);
        }

    }
}