<?php

namespace Ignite\Core\Models\Dashboard\Charts;

use Ignite\Core\Contracts\Dashboard\WithInlineSeries;
use Ignite\Core\Contracts\Dashboard\WithPercentageChange;
use Ignite\Core\Models\Dashboard\Concerns\DeterminesPercentageChange;
use Ignite\Core\Services\Google\Analytics\Client;

class UniqueSessionsStat extends BaseGoogleAnalyticsMetric implements WithInlineSeries, WithPercentageChange
{
    use DeterminesPercentageChange;

    /**
     * @inheritdoc
     */
    public function __construct(Client $analytics, $attributes = [])
    {
        $attributes = array_merge([
            'label' => 'Unique Visitors',
        ], $attributes);

        parent::__construct($analytics, $attributes);
    }

    /**
     * Set the series data. E.g. [day => total]
     *
     * @param array $data
     *
     * @return self
     */
    public function setSeries(array $data)
    {
        $this->offsetSet('series', array_map(function ($value) {
            return (empty($value)) ? 0 : $this->decorate($value);
        }, $data));

        return $this;
    }

    /**
     * Set the percentage change values using current versus previous ranges.
     *
     * @param int|float $current
     * @param int|float $previous
     *
     * @return self
     */
    public function setPercentageChange($current, $previous)
    {
        $direction = $this->determineChangeType($current, $previous);
        $percentage = $this->determinePercentageChange($current, $previous);

        $this->offsetSet('current', number_format($current, 0));
        $this->offsetSet('previous', number_format($previous, 0));
        $this->offsetSet('direction', $direction);
        $this->offsetSet('percentage', $percentage);

        return $this;
    }


    /**
     * @inheritDoc
     */
    public function getElement()
    {
        return $this->get('key', 'unique-sessions-stat');
    }

    /**
     * @inheritDoc
     */
    public function getSize()
    {
        return $this->get('size', 'col-xs-6 col-sm-3');
    }

    /**
     * @inheritDoc
     */
    public function getData()
    {
        return $this->prepareData('sessions');
    }

    /**
     * @inheritDoc
     */
    protected function decorate($value)
    {
        return number_format($value);
    }
}
