<?php

namespace BodyRep\Controller;
use BodyRep\Form\Profile;
use Symfony\Component\HttpFoundation\Response;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\SecurityContext;

# Annotations & templates
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

use JMS\SecurityExtraBundle\Annotation\Secure;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

class MemberController extends Controller
{
    private $member;
    public function setContainer(ContainerInterface $container = null)
    {
      parent::setContainer($container);   
      $db = $this->getDoctrine()->getManager();
      $user = $this->getUser();
      if (method_exists($user, 'getUsername'))
      {      
        $username = $this->getUser()->getUsername();

        $query = $db->createQuery('
                        SELECT m
                        FROM BodyRep:Member m
                        WHERE m.username = :username')                
                    ->setParameter('username', $username)                     
                    ->setMaxResults(1);

         if (sizeof($query->getResult()) != 1)
           throw $this->createNotFoundException("User '".$username."' not found");

        $this->member = $query->getSingleResult();
      }
    }
   
    
    private function getMember()
    {
      return $this->member;
    }
   
    public function navbarAction()
    {
        // The security layer will intercept this request
    }

    /**
     * @Route("/", name="_member")
     * @Template()
     */
    public function indexAction()
    {
      $username = $this->getUser()->getUsername();
   

       return array('name' => $this->getMember()->getFullName());
    }

    /**
     * @Route("/profile/", name="_member_profile")
     * @Template()
     */
    public function profileAction()
    {
      $username = $this->getUser()->getUsername();

      $db = $this->getDoctrine()->getManager();
          $query = $db->createQuery('
                          SELECT p
                          FROM BodyRep:Profile p
                          WHERE p.username = :username')                
                      ->setParameter('username', $username)                     
                      ->setMaxResults(1);
           if (sizeof($query->getResult()) != 1)
             throw $this->createNotFoundException("User '".$username."' not found");

           $profile = $query->getSingleResult();
    
           return (array('sFullName' => $profile->getFullName(), 'name' => $this->getMember()->getFullName()));
    }

    /**
     * @Route("/profile/edit", name="_member_profile_edit")
     * @Template()
     */
    public function editProfileAction()
    {
      $username = $this->getUser()->getUsername();
      $form = $this->get('form.factory')->create(new Profile(), array('fullname' => $this->getMember()->getFullName()));
      $error = '';

      return array('form' => $form->createView(), 'error' => '');    
    }

    /**
     * @Route("/profile/save", name="_member_profile_save")
     */
    public function saveAction()
    {
      $username = $this->getUser()->getUsername();
      $db = $this->getDoctrine()->getManager();
      $json = array('result' => 0);

      $form = $this->get('form.factory')->create(new Profile());
      $request = $this->get('request');


      $form->bind($request);

      if ($form->isValid() && sizeof($_POST) > 0) 
      {
        $json['result'] = 1;
        $d = $form->getClientData();
        $this->getMember()->setFullName($d['fullname']);
        $db->persist($this->getMember());
        $db->flush();
      }

      $resp = new Response (json_encode($json));
      $resp->headers->set('Content-Type', 'application/json');

      return $resp;    
   }
     /**
     * @Route("/search/{param}", name="_member_search", defaults={"param" = 0})
     * @Template()
     */
    public function searchAction($param='')
    {

        /*
         * Integrated suggester response        
         *
         */
       $em = $this->getDoctrine()->getManager();
       $query = $em->createQuery("SELECT m FROM BodyRep:Member m WHERE m.fullname ILIKE '%$param%'");
      
       $res = $query->getResult();
       $resc = sizeof($res);
       $sugg = array();
       /*if ($res > 0)
       {
         foreach ($res as $member)
         {           
           $text = preg_replace('/<br[^\>]*>/i', "\n", $member->getFullname());
           $item['text'] = strip_tags($text);
           $item['html'] = $text; 
           $item['data'] = array('username' => htmlspecialchars($member->getUsername()));
           $sugg[] = $item;
         }
       }
      if (!empty($param))
      {
         $json = array('result' => 1, 'suggestions' => $sugg);
         $resp = new Response (json_encode($json));
         $resp->headers->set('Content-Type', 'text/plain');
         return $resp;    
      }
      else*/
        return array('search' => $res);
    }
}
