<?php

namespace Pandy06269\iCalDrupal;

use Pandy06269\iCalDrupal\includes\DrupalConfigFileReader;
use Pandy06269\iCalDrupal\includes\DrupalDatabaseEventReader;
use Pandy06269\iCalDrupal\includes\DrupalDatabaseEventWriter;
use Pandy06269\iCalDrupal\includes\Event;
use Pandy06269\iCalDrupal\includes\ICSEchoWriter;
use Pandy06269\iCalDrupal\includes\ICSFileReader;

//define('DEBUG', true);
define('DRUPAL_CONFIG_FILE', '../sites/default/settings.php');

function autoload_include_file($class)
{
    $class = substr($class, strlen('Pandy06269\\iCalDrupal\\'));

    $filePath = sprintf('%s/%s.php', __DIR__, str_replace('\\', DIRECTORY_SEPARATOR, $class));
    require_once $filePath;
}

spl_autoload_register('\Pandy06269\iCalDrupal\autoload_include_file');

if (defined('DEBUG') && DEBUG)
{
    ini_set('display_errors', 'on');
}

try
{
    $drupalConfigReader = new DrupalConfigFileReader(DRUPAL_CONFIG_FILE);

    $drupalEventReader = new DrupalDatabaseEventReader($drupalConfigReader);
    $drupalEventReader->open();

    $events = $drupalEventReader->getEvents();
    usort($events, function(Event $x, Event $y)
    {
        if ($x->getStartDate() == $y->getStartDate())
        {
            return 0;
        }
        else if ($x->getStartDate() < $y->getStartDate())
        {
            return -1;
        }
        else
        {
            return 1;
        }
    });

    $drupalEventReader->close();

    header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK', true, 200);
    header('Content-Type: text/plain');

    $icsWriter = new ICSEchoWriter();
    $icsWriter->open();

    /** @var Event $event */
    foreach ($events as $event)
    {
        if ($event->getStartDate() > new \DateTime())
        {
            $icsWriter->write($event);
        }
    }

    $icsWriter->close();
}
catch (\Exception $e)
{
    if (defined('DEBUG') && DEBUG)
    {
        echo sprintf('Caught exception: %s' . PHP_EOL, $e->getMessage());
        echo $e->getTraceAsString();
    }
    else
    {
        echo 'An error occurred';
    }

    header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
}