<?php

namespace OfficeBrain\Bundle\ObSolrOperationBundle\Controller;

use OfficeBrain\Bundle\ObSolrOperationBundle\Form\Data\OperationData;
use OfficeBrain\Bundle\ObSolrOperationBundle\Form\Type\OperationType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\Request;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Process\Process;

class DefaultController extends Controller
{
    /**
     * @Route("/list")
     *
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function listAction(Request $request)
    {
        $listFile = $this->container->getParameter('office_brain_ob_solr_operation.log_folder_path');
        $finder = new Finder();
        $finder->files()->in($listFile)->sortByModifiedTime();
        return $this->render('OfficeBrainObSolrOperationBundle:Default:list.html.twig', array('fileData' => $finder));
    }

    /**
     * @param Request $request
     * @return array
     *
     * @Route("/process")
     * @Template("")
     */
    public function processAction(Request $request)
    {
        $form = new OperationType();
        $data = new OperationData();
        $createForm = $this->createForm($form, $data);
        $createForm->handleRequest($request);

        if ($createForm->isValid() && $request->isMethod("POST")) {
            $data = $createForm->getData();
            $syncService = $this->get('office_brain_ob_solr_operation.sync_service');
            switch ($data->getOperation()) {
                case 'sync_product':
                    $syncService->processProductSyncCommand($data);
                    break;
                /*case 'sync_feature_product':
                    $syncService->processFeatureProductSyncCommand($data);
                    break;*/
                case 'delete_product':
                    $syncService->processDeleteProductCommand($data);
                    break;
                /*case 'delete_feature_product':
                    $data->setIsFeature('yes');
                    $syncService->processDeleteProductCommand($data);
                    break;
                case 'delete_thumbnail':
                    $syncService->processDeleteImagesCommand($data);
                    break;*/
            }

            return new JsonResponse(array("message" => "Command is in queue for solr process.", "flag" => true));
        } else if ($request->isMethod("POST")) {
            return new JsonResponse(array("message" => $createForm->getErrorsAsString(), "flag" => false));
        }
        return array("form" => $createForm->createView());
    }

    /**
     * @param Request $request
     * @return array
     *
     * @Route("/operation/{operation}/{fileName}")
     * @Template("")
     */
    public function processFileAction(Request $request)
    {
        if ($request->get('operation')=="viewFile"){
            $response = new Response(file_get_contents(urldecode($request->get('fileName'))));
            $response->headers->set('Content-Type', 'text/plain');
            return $response;
        } else if($request->get('operation')=="deleteFile") {
            $fileName = urldecode($request->get('fileName'));
            $logFolderPath = $this->container->getParameter('office_brain_ob_solr_operation.log_folder_path');
            $listFile = $this->container->getParameter('office_brain_ob_solr_operation.log_folder_path');
            $finder = new Finder();
            $finder->files()->in($listFile)->sortByModifiedTime();
            foreach ($finder as $file) {
                if($file->getFilename()==$fileName){
                    unlink($file->getRealPath());
                }
            }
            return new Response("File ".$fileName." removed successfully");
        } else {
            return new Response("No Action Deleted");
        }
    }

    /**
     * @Route("/list-running-process")
     * @Template("")
     */
    public function listRunningProcessAction()
    {
        $process = new Process('ps aux| grep office');
        $process->run();
        $response = new Response();
        $response->setContent(nl2br($process->getOutput()));
        $response->headers->set('Content-Type', 'text/plain');
        return $response;
    }
}
