<?php

namespace App\Http\Controllers;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

use App\Services\Dav\LaravelSabreAuthBackend;
use App\Services\Dav\LaravelSabrePrincipalBackend;

use Sabre\DAV;
use Sabre\DAV\Auth\Plugin as AuthPlugin;
use Sabre\DAVACL\Plugin as ACLPlugin;
use Sabre\DAVACL\PrincipalCollection;
use Sabre\CalDAV\CalendarRoot;
use Sabre\CalDAV\Plugin as CalDavPlugin;
use Sabre\CalDAV\Backend\PDO as CalDAVPDO;
use Sabre\CalDAV\Subscriptions\Plugin as SubscriptionsPlugin;
use Sabre\CardDAV\AddressBookRoot;
use Sabre\CardDAV\Plugin as CardDavPlugin;
use Sabre\CardDAV\Backend\PDO as CardDAVPDO;

class DavController extends Controller
{
    public function handle()
    {
        // debug
        \Log::info('SabreDAV DavController');

        // get raw pdo from laravel
        $pdo = DB::connection()->getPdo(); // get raw PDO from Laravel

        // setup the backends
        $authBackend = new LaravelSabreAuthBackend();
        $principalBackend = new LaravelSabrePrincipalBackend();
        $calendarBackend = new CalDAVPDO($pdo);
        $cardBackend = new CardDAVPDO($pdo);

        $nodes = [
            new PrincipalCollection($principalBackend),
            new CalendarRoot($principalBackend, $calendarBackend),
            new AddressBookRoot($principalBackend, $cardBackend)
        ];

        $server = new DAV\Server($nodes);
        $server->setBaseUri('/dav/');

        $server->addPlugin(new AuthPlugin($authBackend, 'Kithkin DAV'));
        $server->addPlugin(new ACLPlugin());
        $server->addPlugin(new CalDavPlugin());
        $server->addPlugin(new CardDavPlugin());
        $server->addPlugin(new SubscriptionsPlugin());

        $server->on('beforeMethod', function () {
            \Log::info('SabreDAV beforeMethod triggered');
        });

        $server->exec();
        exit;
    }
}
