<?php
/**
 * Created by PhpStorm.
 * User: Olyanren
 * Date: 28.10.2016
 * Time: 19:47
 */

namespace AppBundle\Controller;


use AppBundle\Entity\Mac;
use AppBundle\Entity\Person;
use AppBundle\Entity\Product;
use Doctrine\DBAL\Exception\UniqueConstraintViolationException;
use Exception;
use ReflectionObject;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

class DefaultController extends Controller
{
    /**
     * @Route("/")
     */
    public function index()
    {
        return $this->redirect('/7073a00e724bbda643cb7e2a85110640/home');
    }


    /**
     * @Route("/save-user-with-mac-addres")
     */
    public function saveMacAddress(Request $request)
    {
        $name = $request->request->get("name");
        $surname = $request->request->get("surname");
        $email = $request->request->get("email");
        $phone = $request->request->get("phone");
        $address = $request->request->get("address");
        $macValue = $request->request->get("mac");

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            return new Response("false");
        }
        $dql = "SELECT m.value as value FROM AppBundle:Mac m WHERE m.value=:value";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql)
            ->setParameter('value', $macValue);
        $result = $query->getResult();
        if (count($result) == 0) {
            try {
                $mac = new Mac();
                $mac->setValue($macValue);
                $product = new Product();
                $product->setName("default");
                $product->setMac($mac);
                $product->setProductGroup($this->get("app.doctrineutil")->getDefaultProductGroup());
                $mac->setProduct($product);
                $person = new Person();
                $person->setUsername($email);
                $person->setPassword($email);
                $person->setName($name);
                $person->setSurname($surname);
                $person->setEmail($email);
                $person->setTelephone($phone);
                $person->setAddress($address);
                $person->setProduct($product);
                $product->setPerson($person);
                $em->persist($mac);
                $em->persist($product);
                $em->persist($person);
                $em->flush();
                return new Response("OK");
            } catch (UniqueConstraintViolationException $e) {
                $this->get('logger')->error($e->getMessage());
                return new Response("Daha önce kayıt olunmuş. Lütfen yöneticiye başvurunuz");
            } catch (Exception $e) {
                $this->get('logger')->error($e->getMessage());
                return new Response("Kayıt işlemi gerçekleştirilirken hata oluştu. Lütfen daha sonra tekrar deneyiniz");
            }
        } else {
            return new Response("OK");
        }
    }

    /**
     * @Route("/is-user-registered")
     */
    public function isUserRegistered(Request $request)
    {
        $mac = $request->query->get("mac");
        $dql = "SELECT '1' FROM AppBundle:Mac m INNER JOIN m.product p INNER JOIN p.person person WHERE m.value=:value";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql)
            ->setParameter('value', $mac);
        $result = $query->getResult();
        return new Response(count($result) > 0 ? 'true' : 'false');
    }
    /**
     * @Route("/get-super-admin-password")
     */
    public function getSuperAdminPassword(Request $request)
    {
        $superAdminRequest = $request->query->get("superadmin");
        if($superAdminRequest=="234234refasfsfvsdfsadfasdr33")
			return new Response('12345678');
		else
			return new Response('');
    }
    /**
     * @Route("/get-start-date")
     */
    public function getStartDate(Request $request)
    {
        $mac = $request->query->get("mac");
        $dql = "SELECT p.startDate as startDate FROM AppBundle:Mac m INNER JOIN m.product p WHERE m.value=:value";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql)
            ->setParameter('value', $mac);
        $result = $query->getResult();
        if (count($result) != 0) {
            return new Response($this->getDateFromDateTime($result[0]["startDate"]));
        } else {
            return new Response("false");
        }
    }

    /**
     * @Route("/get-end-date")
     */
    public function getEndDate(Request $request)
    {
        $mac = $request->query->get("mac");
        $dql = "SELECT p.endDate as endDate FROM AppBundle:Mac m INNER JOIN m.product p WHERE m.value=:value";
        $em = $this->getDoctrine()->getManager();
        $query = $em->createQuery($dql)
            ->setParameter('value', $mac);
        $result = $query->getResult();
        if (count($result) != 0) {
            return new Response($this->getDateFromDateTime($result[0]["endDate"]));
        } else {
            return new Response("false");
        }
    }
   private function getDateFromDateTime($datetime){
       return  $datetime->format('Y-m-d H:i:s').'.000000';
    }

}