<?php

const SECONDS_IN_A_MINUTE = 60;
const TIME_FORMAT = 'H:i';
const TIME_FORMAT_INC_SECONDS = 'H:i:s';
const DATE_AND_TIME_FORMAT_NO_TZ = 'Y-m-d\TH:i';

$GB_TIMEZONE_NAME = "Europe/London";
$GB_TIMEZONE = new DateTimeZone($GB_TIMEZONE_NAME);

function minutes_later(DateTime $time1, DateTime $time2)
{
    return (int) (($time2->getTimestamp() - $time1->getTimestamp()) / SECONDS_IN_A_MINUTE);
}

function in_num_minutes(DateTime $time2)
{
    global $GB_TIMEZONE;

    return minutes_later(new DateTime("now", $GB_TIMEZONE), $time2);
}

function compare_real_times(ServiceAtStop $service1, ServiceAtStop $service2)
{
    // Prefer departure over arrival, *real-time over scheduled*
    $service1DT = (isset($service1->AtThisLocation()->departure) ?
        ((isset($service1->AtThisLocation()->departure->realTime) && !$service1->AtThisLocation()->isCancelled) ? $service1->AtThisLocation()->departure->realTime : $service1->AtThisLocation()->departure->scheduled) : ((isset($service1->AtThisLocation()->arrival->realTime) && !$service1->AtThisLocation()->isCancelled) ? $service1->AtThisLocation()->arrival->realTime : $service1->AtThisLocation()->arrival->scheduled));
    $service2DT = (isset($service2->AtThisLocation()->departure) ?
        ((isset($service2->AtThisLocation()->departure->realTime) && !$service2->AtThisLocation()->isCancelled) ? $service2->AtThisLocation()->departure->realTime : $service2->AtThisLocation()->departure->scheduled) : ((isset($service2->AtThisLocation()->arrival->realTime) && !$service2->AtThisLocation()->isCancelled) ? $service2->AtThisLocation()->arrival->realTime : $service2->AtThisLocation()->arrival->scheduled));

    return $service1DT->getTimestamp() - $service2DT->getTimestamp();
}

function compare_scheduled_times(ServiceAtStop $service1, ServiceAtStop $service2)
{
    // Prefer departure over arrival, *scheduled over real-time*
    $service1DT = (isset($service1->AtThisLocation()->departure) ?
        (isset($service1->AtThisLocation()->departure->scheduled) ? $service1->AtThisLocation()->departure->scheduled : $service1->AtThisLocation()->departure->realTime) : (isset($service1->AtThisLocation()->arrival->scheduled) ? $service1->AtThisLocation()->arrival->scheduled : $service1->AtThisLocation()->arrival->realTime));
    $service2DT = (isset($service2->AtThisLocation()->departure) ?
        (isset($service2->AtThisLocation()->departure->scheduled) ? $service2->AtThisLocation()->departure->scheduled : $service2->AtThisLocation()->departure->realTime) : (isset($service2->AtThisLocation()->arrival->scheduled) ? $service2->AtThisLocation()->arrival->scheduled : $service2->AtThisLocation()->arrival->realTime));

    return $service1DT->getTimestamp() - $service2DT->getTimestamp();
}

function sort_board_entries_by_time($services, $compareRealTime = true)
{
    $compareRealTime ? usort($services, 'compare_real_times') : usort($services, 'compare_scheduled_times');
    return $services;
}
