<?php

namespace Ignite\Core\Models\Grid;

use Ignite\Core\Entities\Audit;
use Ignite\Core\Models\Grid\EloquentTable;
use Ignite\Core\Models\Grid\HistoryFormatter;
use Illuminate\Database\DatabaseManager;
use Illuminate\Database\Eloquent\Model;
use Yajra\DataTables\DataTables;

class GenericHistoryTable extends EloquentTable
{
    /**
     * @var Model
     */
    protected $model;

    /**
     * @var HistoryFormatter
     */
    protected $formatter;

    /**
     * ParticipantTable constructor.
     *
     * @param DataTables       $datatables
     * @param DatabaseManager  $databaseManager
     * @param HistoryFormatter $formatter
     * @param array            $params
     */
    public function __construct(
        DataTables $datatables,
        DatabaseManager $databaseManager,
        HistoryFormatter $formatter,
        array $params = []
    ) {
        parent::__construct($datatables, $databaseManager, $params);
        $this->formatter = $formatter;
    }

    /**
     * The columns to show.
     *
     * @return array
     */
    public function columns()
    {
        return [
            'created_at' => [
                'title' => 'Created',
                'name' => 'created_at',
                'orderable' => true,
                'exportable' => true
            ],
            'user_id' => [
                'title' => 'Changed By',
                'name' => 'user_id',
                'orderable' => true,
                'exportable' => true,
            ],
            'event' => [
                'title' => 'Event',
                'name' => 'event',
                'orderable' => true,
                'exportable' => true,
            ],
            'old_values' => [
                'title' => 'Message',
                'name' => 'old_values',
                'orderable' => true,
                'exportable' => true,
            ],
        ];
    }

    /**
     * The Product history query.
     *
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public function query()
    {
        return Audit::with('user')
            ->where('context_type', get_class($this->model))
            ->where('context_id', $this->model->getKey());
    }

    /**
     * Sets the model
     *
     * @param Model $model
     * @return self
     */
    public function setModel(Model $model)
    {
        $this->model = $model;

        return $this;
    }

    /**
     * Get a map of column keys => functions to format columns.
     *
     * @return array
     */
    protected function getColumnFormattingMap()
    {
        return [
            'created_at' => [$this->formatter, 'createdAt'],
            'user_id' => [$this->formatter, 'user'],
            'event' => [$this->formatter, 'event'],
            'old_values' => [$this->formatter, 'message'],
        ];
    }
}
