<?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\Models\User;
use ModulesGarden\HostingQuotaNotifications\App\Models\Usage;
use ModulesGarden\HostingQuotaNotifications\App\UI\Services\Buttons\UsageButton;
use ModulesGarden\HostingQuotaNotifications\App\UI\Services\Providers\ServicesProvider;
use ModulesGarden\HostingQuotaNotifications\Core\Helper\BuildUrl;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Interfaces\AdminArea;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataProviders\Providers\ArrayDataProvider;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataTable;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\Column;
use ModulesGarden\HostingQuotaNotifications\Core\UI\Widget\DataTable\DataProviders\DataProvider;

/**
 * Class ServicesPage
 *
 * @author Artur Pilch <artur.pi@modulesgarden.com>
 */
class ServicesPage extends DataTable implements AdminArea
{
    protected $id   = 'services_id';
    protected $name = 'services_name';

    protected function loadHtml()
    {
        $this
            ->addColumn((new Column('service'))
                ->setSearchable(true, Column::TYPE_INT)
                ->setOrderable(DataProvider::SORT_ASC))
            ->addColumn((new Column('client'))
                ->setSearchable(true)
                ->setOrderable())
            ->addColumn((new Column('productName'))
                ->setSearchable(true)
                ->setOrderable())
            ->addColumn((new Column('domain'))
                ->setOrderable()
                ->setSearchable(true));
    }

    protected function loadData()
    {

        $provider = new ServicesProvider();
        $dataProv = new ArrayDataProvider();
        $dataProv->setData($provider->getServices());
        $dataProv->setDefaultSorting('hostingId', DataProvider::SORT_ASC);
        $this->setDataProvider($dataProv);
    }

    public function initContent()
    {
        $this->appendActionButtons();
    }


    protected function appendActionButtons()
    {
        $usage = new UsageButton();
        $usage->setRawUrl(BuildUrl::getUrl('Services', 'usage'))
            ->setRedirectParams(['serviceid' => ':id']);
        $this->addActionButton($usage);

        $this->addActionButton((new UsageButton()));
    }

    public function replaceFieldService($key, $row)
    {
        return sprintf(Hosting::URL, $row['userid'], $row['id'], '', $row['id']);
    }

    public function replaceFieldClient($key, $row)
    {
        return sprintf(User::URL, $row['userid'], $row['client']);
    }

    public function replaceFieldProductName($key, $row)
    {
        return sprintf(Product::URL, $row['packageid'], $row['productName']);
    }
}