<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin\AdminBar\Filler;

use ActiveRecord\Profiler\ProfilerInterface;
use Application\Admin\AdminBar\AdminBar;
use Application\Admin\AdminBar\FillerInterface;
use Pongho\Menu\Item;

class DbProfilerFiller implements FillerInterface
{
    /**
     * @var ProfilerInterface
     */
    protected $profiler;

    public function __construct(ProfilerInterface $profiler)
    {
        $this->profiler = $profiler;
    }

    /**
     * {@inheritdoc}
     */
    public function fill(AdminBar $admin_bar)
    {
        $item = new Item(
            sprintf(
                '%d query / %s sec',
                $this->profiler->count(),
                number_format($this->profiler->getDeltaTime(), 3)
            )
        );

        $item->setId('pongho-db-profiler');

        $admin_bar->left->add($item);

        $admin_bar->addHtml($this->getHtmlCode());
        $admin_bar->addCss($this->getCssCode());
        $admin_bar->addJs($this->getJsCode());
    }

    private function getHtmlCode()
    {
        return <<<HTML
<div id="pongho-db-profiler-panel">
    <div class="pongho-modal-overlay"></div>
    <section class="pongho-modal">
        <header><button id="sort-by-time">Order by delta time</button> <button id="sort-by-history">Order by history</button></header>
        <ul></ul>
    </section>
</div>
HTML;
    }

    private function getCssCode()
    {
        return file_get_contents(__DIR__ . '/../../Resources/public/adminbar/db-profiler/style.css');
    }

    private function getJsCode()
    {
        $queries = 'var DBQueries = ' . $this->getQueryList() . ';';

        return $queries . file_get_contents(__DIR__ . '/../../Resources/public/adminbar/db-profiler/script.min.js');
    }

    /**
     * @return string
     */
    private function getQueryList()
    {
        $counter = 0;
        $queries = [];

        foreach ($this->profiler as $query) {
            $queries[] = [
                'history' => ++$counter,
                'query'   => $query['query'],
                'values'  => $this->convertValuesToString($query['values']),
                'time'    => $query['delta_time'],
            ];
        }

        return json_encode($queries);
    }

    /**
     * @param mixed $var
     * @return string
     */
    private function convertValuesToString($var)
    {
        switch (gettype($var)) {
            case 'array':
                $to_implode = [];

                if (is_hash($var)) {
                    foreach ($var as $key => $value) {
                        $to_implode[] = "'{$key}' => " . var_to_string($value);
                    }
                } else {
                    foreach ($var as $value) {
                        $to_implode[] = var_to_string($value);
                    }
                }

                return '[ ' . implode(', ', $to_implode) . ' ]';

            default:
                return var_to_string($var);
        }
    }
}
