<?php

//
// sorts an array of named arrays by the supplied fields
//   code by dholmes at jccc d0t net
//   taken from http://au.php.net/function.uasort
// modified by cablehead, messju and pscs at http://www.phpinsider.com/smarty-forum

use KupShop\KupShopBundle\Context\LanguageContext;
use KupShop\KupShopBundle\Util\Contexts;

function array_sort_by_fields(&$data, $sortby)
{
    static $sort_funcs = [];

    if ($data === '') {
        return;
    }

    if (empty($sort_funcs[$sortby])) {
        $sortData = [];
        // prepare sort
        foreach (explode(',', $sortby) as $key) {
            $d = 1;
            $c = 0;
            if (substr($key, 0, 1) == '-') {
                $d = -1;
                $key = substr($key, 1);
            }

            if (substr($key, 0, 1) == '#') {
                $key = substr($key, 1);
                $sortCallable = function ($a, $b) use ($key, $d, $c) {
                    if ($a[$key] > $b[$key]) {
                        return $d * 1;
                    }

                    if ($a[$key] < $b[$key]) {
                        return $d * -1;
                    }

                    return $c;
                };
            } else {
                $collator = new Collator(Contexts::get(LanguageContext::class)->getActive()->getLocale());
                $sortCallable = function ($a, $b) use ($key, $d, $c, $collator) {
                    if (($c = $collator->compare($a[$key], $b[$key])) != 0) {
                        return $d * $c;
                    }

                    return $c;
                };
            }

            $sortData[$key] = $sortCallable;
        }

        // create sort func
        $sort_func = $sort_funcs[$sortby] = function ($a, $b) use ($sortData) {
            foreach ($sortData as $key => $callable) {
                return $callable($a, $b);
            }

            return 0;
        };
    } else {
        $sort_func = $sort_funcs[$sortby];
    }
    uasort($data, $sort_func);
}

//
// Modifier: sortby - allows arrays of named arrays to be sorted by a given field
//
function smarty_modifier_sortby($arrData, $sortfields)
{
    array_sort_by_fields($arrData, $sortfields);

    return $arrData;
}

// $smarty->register_modifier( "sortby", "smarty_modifier_sortby" );
