<?php

namespace AppBundle\Controller\Front;

use AppBundle\Entity\Core\Metric;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

/**
 * @author Guillaume Cavana <guillaume.cavana@gmail.com>
 */
class MetricController extends Controller
{
    /**
     * listMetricAction.
     *
     * @return \Symfony\Component\HttpFoundation\Response A Response instance
     */
    public function listMetricAction()
    {
        $metrics = $this->getDoctrine()
                ->getRepository('AppBundle:Core\Metric')
                ->findDisplayedMetrics();

        return $this->render('Metric/list.html.twig', [
        'metrics' => $metrics, ]);
    }

    /**
     * @Route("/metrics/{uuid}/{period}",
     *         name="ajax_get_metric_point",
     *         requirements={"period" = "day|week|month"},
     *         defaults={"period"="day"}
     * )
     *
     * @Method("GET")
     *
     * @param Request $request
     * @param Metric  $metric
     * @param string  $period
     *
     * @return \Symfony\Component\HttpFoundation\JsonResponse A JsonResponse instance
     */
    public function getMetricPointDataAction(Request $request, Metric $metric, $period)
    {
        switch ($period) {
            case 'week':
                $metricPoints = $this->getDoctrine()
                    ->getRepository('AppBundle:Core\MetricPoint')
                    ->findWeekMetricPointByDay($metric);
                break;
            case 'month':
                $metricPoints = $this->getDoctrine()
                    ->getRepository('AppBundle:Core\MetricPoint')
                    ->findMonthMetricPointByDay($metric);
                break;
            default:
                $metricPoints = $this->getDoctrine()
                    ->getRepository('AppBundle:Core\MetricPoint')
                    ->findTodayMetricPointByHour($metric);
                break;
        }

        $json['metrics']['metric'] = [
            'uuid' => $metric->getUuid(),
            'name' => $metric->getName(),
            'description' => $metric->getDescription(),
            'metric_type' => $metric->getMetricType(),
            'metric_calc' => $metric->getMetricCalc(),
        ];

        $data = [];
        foreach ($metricPoints as $i => $point) {
            $data[$i]['label'] = $point['label'];
            $data[$i]['value'] = round($point['value'], $this->container->getParameter('app_metric_precision'));
        }

        $json['metrics']['data'] = $data;

        return new JsonResponse($json, 200, ['Access-Control-Allow-Origin' => '*']);
    }
}
