<?php
/**
 * Created by PhpStorm.
 * User: robin
 * Date: 9/30/16
 * Time: 8:58 PM
 */

namespace App\Business;


use App\DataAccess\StopsDataAccess;
use App\Dbo\StopsDbo;
use Luticate\Utils\Dbo\LuPaginatedDbo;

class StopsBusiness
{
    protected static function getDataAccess()
    {
        return new StopsDataAccess();
    }

    public static function getStopDboById(array $dbos, string $id)
    {
        /**
         * @var $dbos StopsDbo[]
         */
        foreach ($dbos as $dbo) {
            if ($dbo->getId() == $id) {
                return $dbo;
            }
        }
        return null;
    }

    public static function mergeStringArray(array $array1, array $array2)
    {
        foreach ($array2 as $e) {
            if (!in_array($e, $array1)) {
                $array1[] = $e;
            }
        }
        return $array1;
    }

    public static function getAll()
    {
        $config = MiscBusiness::getConfig();
        $dbos = [];
        foreach ($config["scheduleTypes"] as $scheduleType) {
            $scheduleDbos = static::getDataAccess()->getAll($scheduleType["resourceId"], $scheduleType["type"]);
            foreach ($scheduleDbos as $scheduleDbo) {
                $dbo = static::getStopDboById($dbos, $scheduleDbo->getId());
                if (is_null($dbo)) {
                    $dbos[] = $scheduleDbo;
                }
                else {
                    $dbo->setRoutes(static::mergeStringArray($dbo->getRoutes(), $dbo->getRoutes()));
                }
            }
        }
        usort($dbos, function ($dbo1, $dbo2)
        {
            /**
             * @var $dbo1 StopsDbo
             * @var $dbo2 StopsDbo
             */
            return intval($dbo1->getId()) > intval($dbo2->getId());
        });
        return new LuPaginatedDbo(count($dbos), $dbos);
    }
}