<?php

namespace Ignite\Core\Models\Grid\Button;

/**
 * Sample usage:
 *   protected function getBuilderButtons(array $buttons = []): array
 *   {
 *       $buttons = parent::getBuilderButtons($buttons);
 *       array_unshift($buttons, resolve(ClearSelect::class)->button(0));
 *       return $buttons;
 *   }
 */
class ClearSelect
{
    /**
     * @param int $columnNum
     * @return array
     */
    public function button(int $columnNum = 0): array
    {
        return [
            'text' => 'Clear All (0 selected)',
            'className' => 'btn-clear-selected',
            'init' => 'function (dt, node, config) { ' . $this->init($columnNum) . ' }',
            'action' => "function ( e, dt, node, config ) { dt.column({$columnNum}).checkboxes.deselectAll(); }",
        ];
    }

    /**
     * Returns javascript to initialize the button.
     *
     * @param  int    $columnNum
     * @return string
     */
    protected function init(int $columnNum): string
    {
        $js = <<<JS
buttonNode = $(node);
dt.on('select.dt.DT deselect.dt.DT draw.dt.DT', function() {
    // it needs a little delay
    setTimeout(function() {
        var count = dt.column($columnNum).checkboxes.selected().length;
        buttonNode.text('Clear All (' + count + ' selected)');
    }, 500);
});
JS;
        $js = preg_replace('/\/\/.*/', '', $js);
        $js = preg_replace('/\n/', ' ', $js);
        $js = preg_replace('/\s+/', ' ', $js);

        return $js;
    }
}
