<?php

namespace ModulesGarden\HostingQuotaNotifications\App\UI\Services\Pages;

use ModulesGarden\HostingQuotaNotifications\App\Helper\Models\Hosting;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Models\Product;
use ModulesGarden\HostingQuotaNotifications\App\Helper\Request;
use ModulesGarden\HostingQuotaNotifications\App\Libs\Usage\Manage;
use ModulesGarden\HostingQuotaNotifications\App\Models\Usage;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Interfaces\AdminArea;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\Column;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataProviders\DataProvider;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataTable;
use ModulesGarden\HostingQuotaNotifications\App\Libs\Groups\Constants as GroupConstants;
/**
 * Class ServiceUsagePage
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class ServiceUsagePage extends DataTable implements AdminArea
{
    protected $id   = 'servicesUsageId';
    protected $name = 'servicesUsageName';
    CONST SERVICE_URL = '<a href= "clientsservices.php?userid=%s&id=%s">#%s </a>&nbsp;%s';

    protected function loadHtml()
    {

        $this->setCustomRawTitle();
        $this
            ->addColumn((new Column('id'))
                ->setSearchable(true, Column::TYPE_INT)
                ->setOrderable(DataProvider::SORT_DESC))
            ->addColumn((new Column('bw'))
                ->setSearchable(true)
                ->setOrderable())
            ->addColumn((new Column('disk'))
                ->setSearchable(true)
                ->setOrderable())
            ->addColumn((new Column('date'))
                ->setSearchable(true)
                ->setOrderable());

    }

    protected function loadData()
    {
        $provider = new Manage();
        $dataProv = new ArrayDataProvider();
        $dataProv->setData($provider->getUsages(Request::getValue('serviceid')));
        $dataProv->setDefaultSorting('id', DataProvider::SORT_DESC);
        $this->setDataProvider($dataProv);
    }

    public function replaceFieldBw($key, $row)
    {
        return $row[$key] . ' ' . GroupConstants::MB;
    }

    public function replaceFieldDisk($key, $row)
    {
        return $row[$key] . ' ' . GroupConstants::MB;
    }

    public function setCustomRawTitle()
    {
        $hosting = Hosting::getHostingById(Request::getValue('serviceid'));
        if(!$hosting)
        {
            return;
        }
        $productName = Product::getValueById($hosting->packageid, 'name');
        $show = '#%s %s (%s)';
        $this->setRawTitle(sprintf($show, $hosting->id, $hosting->domain, $productName));
    }
}