<?php

namespace Ignite\Core\Models\Grid;

use Illuminate\Database\DatabaseManager;
use Ignite\Core\Entities\Note;
use Illuminate\Database\Eloquent\Builder;
use Yajra\DataTables\DataTables;

class ParticipantNotesTable extends EloquentTable
{
    /**
     * The excluded column keys.
     * @var array
     */
    protected $excludedKeys = [];

    /**
     * The column keys that should be always visible.
     * @var array
     */
    protected $alwaysVisible = [];

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

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

        $this->formatter = $formatter;
    }

    /**
     * The columns to show.
     *
     * @return array
     */
    public function columns(): array
    {
        return [
            'created_at' => [
                'title' => 'Created',
                'name' => 'created_at',
                'orderable' => true,
                'exportable' => true,
            ],
            'by_user_id' => [
                'title' => 'Added By',
                'name' => 'by_user_id',
                'orderable' => true,
                'exportable' => true,
            ],
            'message' => [
                'title' => 'Description',
                'name' => 'message',
                'orderable' => true,
                'exportable' => true,
            ],
        ];
    }

    /**
     * The participant notes query.
     *
     * @return Builder
     */
    public function query(): Builder
    {
        return $this->applyScopes(
            Note::with('addedBy')->where('table_primary_id', $this->user_id)
        );
    }

    /**
     * Get a map of column keys => functions to format columns.
     *
     * @return array
     */
    protected function getColumnFormattingMap(): array
    {
        return [
            'by_user_id' => function ($model) { return $this->formatter->addedBy($model); },
            'message' => function ($model) { return $this->formatter->message($model); },
        ];
    }

    /**
     * Get default builder parameters.
     *
     * @return array
     */
    protected function getBuilderParameters(): array
    {
        return parent::getBuilderParameters([
            'order' => [
                [0, 'desc'] // Created At
            ]
        ]);
    }
}
