<?php

namespace App\Repositories\Core;

class Arrays
{
    public static function changeKeyName($array, $newkey, $oldkey)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $array[$key] = self::changeKeyName($value, $newkey, $oldkey);
            } else {
                $array[$newkey] = $array[$oldkey];
            }
        }
        unset($array[$oldkey]);

        return $array;
    }

    public static function slotify($array, $length)
    {
        // Create a placeholder array and calculate the number of items
        // needed per slot (think card dealing LtoR).
        for ($slots = array_fill(0, $length, 0), $count = count($array), $i = 0; $i < $count; $slots[$i % $length]++, $i++);

        // Now just take slices of the original array
        // depending on the calculated slot number and place in our slots
        foreach ($slots as $k => $n) {
            $slots[$k] = array_splice($array, 0, $n);
        }

        return $slots;
    }

    public static function alternate_chunk($array, $parts)
    {
        $t = 0;
        $result = [];
        $max = ceil(count($array) / $parts);
        foreach (array_chunk($array, $max) as $v) {
            if ($t < $parts) {
                $result[] = $v;
            } else {
                foreach ($v as $d) {
                    $result[] = [$d];
                }
            }
            $t += count($v);
        }

        return $result;
    }

    public static function fill_chunk($array, $parts)
    {
        $t = 0;
        $result = array_fill(0, $parts - 1, []);
        $max = ceil(count($array) / $parts);
        foreach ($array as $v) {
            count($result[$t]) >= $max and $t++;
            $result[$t][] = $v;
        }

        return $result;
    }
}
