<?php

/**
 * Atmail_Dav_ABookBackend 
 * 
 * @package Atmail
 * @subpackage Dav
 * @copyright Copyright (C) 2011 Atmail Inc. All rights reserved.
 * @author Evert Pot (http://www.rooftopsolutions.nl/) 
 */
class Atmail_Dav_Backend_Abook extends Sabre_CardDAV_Backend_Abstract {

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

        // Since we use the principal uri as the addressbook id, we can just 
        // slice off the last bit and assume that's the account name.
        return new contacts(array('Account' => basename($addressBookId))); 
    }

    /**
     * Returns the list of addressbooks for a specific user. 
     * 
     * @param string $principalUri 
     * @return array 
     */
    public function getAddressBooksForUser($principalUri) {

        // For now we're going to just expose 1 addressbook
        return array(
            array(
                'id' => $principalUri,
                'uri' => 'personal',
                'principaluri' => $principalUri
            ),
        );

    }

    /**
     * Updates an addressbook's properties
     *
     * See Sabre_DAV_IProperties for a description of the mutations array, as 
     * well as the return value. 
     *
     * @param mixed $addressBookId
     * @param array $mutations
     * @see Sabre_DAV_IProperties::updateProperties
     * @return bool|array
     */
    public function updateAddressBook($addressBookId, array $mutations) {

        // We don't allow updating of any properties at the moment
        return false;

    }

    /**
     * Creates a new address book 
     *
     * @param string $principalUri 
     * @param string $url Just the 'basename' of the url. 
     * @param array $properties 
     * @return void
     */
    public function createAddressBook($principalUri, $url, array $properties) {

        throw new Sabre_DAV_Exception_MethodNotAllowed('Creation of new addressbooks is currently not allowed');

    }

    /**
     * Deletes an entire addressbook and all its contents
     *
     * @param int $addressBookId 
     * @return void
     */
    public function deleteAddressBook($addressBookId) {

        throw new Sabre_DAV_Exception_MethodNotAllowed('Deleting of addressbooks is not allowed');

    }

    /**
     * Returns all cards for a specific addressbook id. 
     * 
     * @param mixed $addressbookId 
     * @return array 
     */
    public function getCards($addressBookId) {

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

        $cards = array();

        foreach($contacts as $contact) {

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

        }

        return $cards;

    }

    /**
     * Returns a specfic card
     * 
     * @param mixed $addressBookId 
     * @param string $cardUri 
     * @return void
     */
    public function getCard($addressBookId, $cardUri) {

        $contact = $this->fetchCardByUrl($addressBookId, $cardUri);

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

    }

    /**
     * Creates a new card
     * 
     * @param mixed $addressBookId 
     * @param string $cardUri 
     * @param string $cardData 
     * @return bool 
     */
    public function createCard($addressBookId, $cardUri, $cardData) {

        $model = $this->getModel($addressBookId);
        $contact = Atmail_Dav_ContactMapper::mapVCardToContact($cardData);
        $contact['CardDAVUrl'] = $cardUri;
        $contact['ServerID'] = null;
        $model->addContact($contact);

    }

    /**
     * Updates a card
     * 
     * @param mixed $addressBookId 
     * @param string $cardUri 
     * @param string $cardData 
     * @return bool 
     */
    public function updateCard($addressBookId, $cardUri, $cardData) {

        $model = $this->getModel($addressBookId);

        $contact = $this->fetchCardByUrl($addressBookId, $cardUri);
        $newContact = Atmail_Dav_ContactMapper::mapVCardToContact($cardData);
        $contact = array_merge($contact, $newContact);
         
        $model->updateContact($contact);         

    }

    /**
     * Deletes a card
     * 
     * @param mixed $addressBookId 
     * @param string $cardUri 
     * @return bool 
     */
    public function deleteCard($addressBookId, $cardUri) {

        $model = $this->getModel($addressBookId);

        $contact = $this->fetchCardByUrl($addressBookId, $cardUri);
        $model->deleteContact($contact);

    }

    /**
     * Grabs a card-array from the array based on a carddav url.
     * 
     * @param mixed $addressBookId 
     * @param string $cardUri 
     * @return array 
     */
    public function fetchCardByUrl($addressBookId, $cardUri) {

        $model = $this->getModel($addressBookId);
        if (preg_match('/^atmailid-([0-9]*)\.vcf$/', $cardUri, $matches)) {
            $contact = $model->getContact($matches[1]);
            if (!$contact) throw new Sabre_DAV_Exception_FileNotFound('Contact with id ' . $matches[1] . ' not found');
        } else {
            $contact = $model->getContactByCardDAVUrl($cardUri);
            if (!$contact) throw new Sabre_DAV_Exception_FileNotFound('Contact with url ' . $cardUri . ' not found');
        }
        return $contact;

    }

}
