<?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 AverageSessionDurationStat extends BaseGoogleAnalyticsMetric implements WithInlineSeries, WithPercentageChange
{
    use DeterminesPercentageChange;

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

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

    /**
     * {@inheritdoc}
     */
    public function setSeries(array $data)
    {
        $this->offsetSet('series', array_map(function ($value) {
            return (empty($value)) ? 0 : intval($value);
        }, $data));

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function setPercentageChange($current, $previous)
    {
        $this->offsetSet('current', $this->decorate($current));
        $this->offsetSet('previous', $this->decorate($previous));
        $this->offsetSet('direction', $this->determineChangeType($current, $previous));
        $this->offsetSet('percentage', $this->determinePercentageChange($current, $previous));

        return $this;
    }

    /**
     * {@inheritdoc}
     */
    public function getElement()
    {
        return $this->get('key', 'average-duration-stat');
    }

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

    /**
     * {@inheritdoc}
     */
    public function getData()
    {
        if (Client::VERSION_UA == $this->analytics->getVersion()) {
            return $this->prepareData('avgSessionDuration');
        } else {
            return $this->prepareData('averageSessionDuration');
        }
    }

    /**
     * {@inheritdoc}
     */
    protected function decorate($value)
    {
        $hours = floor($value / 3600);
        $mins = floor($value / 60 % 60);
        $secs = floor($value % 60);

        return sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
    }
}
