<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_Calendar
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * @category  Core
 * @package   Core_Calendar
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */
class Core_Calendar
{
    /**
     * @var array
     */
    protected $_date;

    /**
     * @var Core_Validate_Date
     */
    protected $_dateValidator;

    public function setDate($date)
    {
        $this->_date = $this->_parseDate($date);
        return $this;
    }

    public function getDate()
    {
        if (null === $this->_date) {
            $this->setDate(date('Y-m-d'));
        }
        return $this->_date;
    }

    public function setDateValidator(Core_Validate_Date $dateValidator)
    {
        $this->_dateValidator = $dateValidator;
        return $this;
    }

    public function getDateValidator()
    {
        if (null === $this->_dateValidator) {
            $this->_dateValidator = new Core_Validate_Date;
        }
        return $this->_dateValidator;
    }

    public function getCurrentMonth()
    {
        return new Core_Calendar_Interval_Month;
    }

    protected function _parseDate($date)
    {
        if (is_string($date)) {
            // must be in format YYYY-MM-DD
            $matches = array();
            if (!preg_match('/^(?P<year>[0-9]{4})(-(?P<month>[0-9]{2})(-(?P<day>[0-9]{2}))?)?$/', $date, $matches)) {
                throw new InvalidArgumentException('Invalid date format, must be in format YYYY-MM-DD');
            }

            $date = array(
                'year'  => $matches['year'],
                'month' => $matches['month'],
                'day'   => $matches['day'],
            );
        }

        $validator = $this->getDateValidator();
        if (!$validator->isValid($date)) {
            throw new InvalidArgumentException('Invalid date specified');
        }

        return $date;
    }
}
