<?php

namespace Ignite\Core\Models\Summary;

use Ignite\Core\Facades\Format;
use Ignite\Core\Contracts\MetricInterface;

abstract class AbstractMetric implements MetricInterface
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var float
     */
    protected $total;

    /**
     * @var int
     */
    protected $count;

    /**
     * Metric constructor.
     *
     * @param string $name
     * @param float $total
     * @param int $count
     */
    public function __construct($name, $total, $count)
    {
        $this->name = $name;
        $this->total = $total;
        $this->count = $count;
    }

    /**
     * The name of the metric.
     *
     * @return string
     */
    public function name()
    {
        return $this->name;
    }

    /**
     * The count of the metric.
     *
     * @return mixed
     */
    public function count()
    {
        return $this->count;
    }

    /**
     * The total value/amount of the metric.
     *
     * @param  int $decimals
     * @param  int $default
     * @return string
     */
    public function total($decimals = null, $default = 0)
    {
        return Format::balance($this->total, $decimals, $default);
    }

    /**
     * The percentage of the given total.
     *
     * @param float|int $total
     * @return float|int
     */
    public function percentage($total)
    {
        if ($total <= 0) {
            return 0;
        }

        return $this->count / $total;
    }

    /**
     * Get the configured color name for the metric.
     *
     * @param  string $default
     * @return string
     */
    public function color($default = '#dddddd')
    {
        return $this->statusOrDefault('color', $default);
    }

    /**
     * Get the configured class name for the metric.
     *
     * @param  string $default
     * @return string
     */
    public function style($default = 'default')
    {
        return $this->statusOrDefault('class', $default);
    }

    /**
     * Get the configured order value for the metric.
     *
     * @param  int $default
     * @return int
     */
    public function order($default = 0)
    {
        return $this->statusOrDefault('order', $default);
    }

    /**
     * Try to get the type of data from the status or provide a default.
     *
     * @param  $type
     * @param  $default
     * @return string
     */
    protected function statusOrDefault($type, $default)
    {
        $status = $this->name;

        if (! property_exists($this, $status)) {
            return $default;
        }

        return $this->$status[$type];
    }
}
