<?php

namespace App\Modules\HtlUsage\Application;

use App\Modules\HtlCamp\Domain\IdHtlCamp;

class HtlUsageOrderer {
    private $campData;

    public function __construct() { }

    public function __invoke (string $dateStart, string $dateEnd, $campList) {
        $timeDateStart = strtotime(date('Y-m-d', strtotime($dateStart)));
        $timeDateEnd = strtotime(date('Y-m-d', strtotime($dateEnd)));
        
        $dayInSeconds = 86400;
        $this->campData = $campList['Response_Data'];
        $dateArray = $this->createDateArray($timeDateStart, $timeDateEnd, $dayInSeconds);
        
        $campList['Response_Data'] = $this->createDaysList($dateArray);
        return $campList;
    }

    private function createDaysList($dateArray) {
        return array_map(fn($curdate) => (object)[
                'date' => $curdate,
                'campList' => $this->createCampListByDay($curdate)
            ],
            $dateArray
        );
    }

    private function createCampListByDay($date) {
        $list = [];
        while (count($this->campData) && $this->campData[0]->HtlUsage_DateUsage == $date) {
            $list[] = array_shift($this->campData);
        }
        return $list;
    }

    public function createDateArray(int $initial, int $to, int $sumatory) {
        $arr = [];
        while ($initial < $to) {
            $arr[] = date('Y-m-d', $initial);
            $initial += $sumatory;
        }
        return $arr;
    }

}