<?php

namespace App\Models\Utils;


/*
 * Konvertuje/priprema podatke modela za 'select2 plugin'.
 * Moze da se koristi samo u Laravel modelu.
 */
Trait StaticSelect2ConverterTrait
{
    /**
     * 
     * Generiši JSON podataka iz modela tako da je adekvatan za upotrebu u 
     * 'select2' tj. da moze direktno da se renderuje u 'view'.
     * 
     * @link https://select2.org/data-sources/formats
     * 
     * @param Array $colMap | format: ['id' => col_name, 'text' => col_name]
     * @param string $mode  | moguce vrednosti: 'eloquent', 'raw'
     * 
     *       // -- select2 'data' format -- //
     *       [
     *              {
     *                 "id": 1,
     *                "text": "Option 1"
     *              },
     *              {
     *                "id": 2,
     *                "text": "Option 2"
     *                "selected": true
     *              }
     *       ],
     * 
     * @throws \InvalidArgumentException
     * 
     * @return string | JSON string
     */
    public static function getSelect2SpecData($colMap, $mode="eloquent")
    {
        if( ! is_array($colMap) || ! \Illuminate\Support\Arr::has($colMap, ['id', 'text']) ) {
            throw new \InvalidArgumentException("Neispravan parametar \$colMap"
                                              . " u funkciji " . __METHOD__);
        }

        if($mode == "raw") {
            $dataArr = self::_select2SpecDataRawQuery($colMap);
        }
        else if($mode == "eloquent") {
            $dataArr = self::_select2SpecDataEloquentQuery($colMap);
        }
        else {
            throw new \InvalidArgumentException("Neispravan parametar \$mode "
                . "prilikom pozivanja funkcije " . __METHOD__);
        }

        return json_encode($dataArr, JSON_UNESCAPED_UNICODE);
    }

    /**
     * @return Array
     */
    private static function _select2SpecDataRawQuery($colMap)
    {
        // uzmi ime tabele staticki (predlog Taylor Otwell-a na forumu)
        $tablename = with(new self)->getTable(); 

        $dataArr = \DB::table($tablename)
                        ->select(\DB::raw($colMap['id'] . ' as id, ' . $colMap['text'] . ' as text'))
                        ->get();
        return $dataArr;
    }

    /**
     * @return Array
     */
    private static function _select2SpecDataEloquentQuery($colMap)
    {
        $data = self::get(array_values($colMap));

        $dataArr = $data->map(function($row) use($colMap) {
            $dat = [];
            $dat['id'] = $row[ $colMap['id'] ];
            $dat['text'] = $row[ $colMap['text'] ];
            return $dat;
        });

        return $dataArr;
    }

}