<?php

/**
 * Directory node
 *
 * This node is responsible for the top-level /directory path. This path 
 * contains the Atmail Global addressbook.
 * 
 * @package Atmail
 * @subpackage Dav 
 * @copyright Copyright (C) 2011 Atmail inc. All rights reserved.
 * @author Evert Pot (http://www.rooftopsolutions.nl/) 
 */
class Atmail_Dav_Directory extends Sabre_DAV_Directory implements Sabre_CardDAV_IDirectory {

    /**
     * Authentication plugin 
     * 
     * @var Sabre_DAV_Auth_Plugin
     */
    private $_authPlugin;

    /**
     * Constructor
     * 
     * @param Sabre_DAV_Auth_Plugin $authPlugin
     */
    public function __construct(Sabre_DAV_Auth_Plugin $authPlugin) {

        $this->_authPlugin = $authPlugin;

    }

    /**
     * Nodename
     * 
     * @return string 
     */
    public function getName() {
        
        return 'directory';

    }

    /**
     * Returns all the cards
     * 
     * @return array 
     */
    public function getChildren() {

        $model = $this->getModel();
        $contacts = $model->getContacts(array(
            'GroupID' => GROUP_GLOBAL,
        ));

        $cards = array();

        foreach($contacts as $contact) {

            $cards[] = new Atmail_Dav_DirectoryCard(array(
                'uri' => $contact['CardDAVUrl']?$contact['CardDAVUrl']:'atmailid-' . $contact['id'] . '.vcf',
                'carddata' => Atmail_Dav_ContactMapper::mapContactToVCard($contact),
                'lastmodified' => strtotime($contact['DateModified']),
            ));

        }

        return $cards;

    }

    /**
     * Returns a contacts model for a user
     * 
     * @param string $account Email address 
     * @return contacts 
     */
    protected function getModel() {

        return new contacts(array('Account' => $this->_authPlugin->getCurrentUser())); 
    }
}
