<?php

namespace Ignite\Core\Models\Dashboard;

use Illuminate\Support\Carbon;
use Illuminate\Support\Fluent;
use Ignite\Core\Contracts\Dashboard\Chart as ChartInterface;

abstract class Chart extends Fluent implements ChartInterface
{
    /**
     * Create a new stat instance.
     *
     * @param  array|object $attributes
     */
    public function __construct($attributes = [])
    {
        parent::__construct(array_merge([
            'element' => $this->getElement(),
            'size' => 'col-xs-12 col-sm-6 col-md-4 col-lg-3'
        ], $attributes));
    }

    /**
     * The label to describe the stat.
     *
     * @return string
     */
    public function getLabel()
    {
        return $this->get('label');
    }

    /**
     * The date range from the request.
     *
     * @return array
     */
    public function getDateRange()
    {
        $start = Carbon::createFromFormat('Y-m-d', request()->query('start', now()->startOfYear()->format('Y-m-d')));
        $end = Carbon::createFromFormat('Y-m-d', request()->query('end', now()->format('Y-m-d')));

        return [$start->startOfDay(), $end->endOfDay()];
    }

    /**
     * Process the chart.
     *
     * @return $this
     */
    public function process()
    {
        $this->getData();

        return $this;
    }

    /**
     * Use the cached attributes to generate the chart data.
     *
     * @return $this
     */
    private function cache()
    {
        $cache = app('cache');
        $key = $this->cacheKey();

        if ($cache->has($key)) {
            $this->attributes = $cache->get($key);
            return $this;
        }

        $cache->put($key, $this->attributes, 10);
        $this->getData();

        return $this;
    }

    /**
     * Generate the cache key.
     *
     * @return string
     */
    private function cacheKey()
    {
        $date = md5(vsprintf('%s-%s', $this->getDateRange()));

        return "charts.{$this->getType()}.{$this->getElement()}.{$date}";
    }
}
