<?php
/**
 * Saml cookie handler
 *
 * LICENSE: This Software is the property of Lifestyle Webconsulting GmbH (Aschaffenburg, Germany)
 * and is protected by copyright law - it is NOT Freeware.
 *
 * Any unauthorized use of this software without a valid license
 * is a violation of the license agreement and will be prosecuted by
 * civil and criminal law.
 *
 * @copyright  2015 Lifestyle Webconsulting GmbH
 * @link       http://www.life-style.de
 */

namespace AppBundle\EventListener\Cookie;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use LifeStyle\Tools\SamlBundle\Event\FilterCookieFileEvent;
use LifeStyle\Tools\SamlBundle\Event\CookieFile as CookieFileEvent;

/**
 * Saml cookie handler
 */
class FileHandler implements EventSubscriberInterface
{

    /**
     * Cookie filename
     *
     * @var string
     */
    private $filename;

    /**
     * Path to cookie filename
     *
     * @var string
     */
    private $path;

    /**
     * Load cookie
     *
     * @param FilterCookieFileEvent $filterEvent
     */
    public function onCookieLoad(FilterCookieFileEvent $filterEvent)
    {
        throw new \Exception('TODO!');
        $this->path = $filterEvent->getCookieFile();
        if (null !== $this->filename) {
            $this->path = dirname($this->path) . '/' . trim($this->filename, '/');
        }
        // Create empty cookie file, if not exists
        if (!empty($this->path) && !file_exists($this->path)) {
            $dirname = dirname($this->path);
            if (!file_exists($dirname)) {
                mkdir($dirname, 0700, true);
            }
            file_put_contents($this->path, '');
        }
        $filterEvent->setCookieFile($this->path);
    }

    /**
     * Remove cookie
     *
     * @param FilterCookieFileEvent $filterEvent
     */
    public function onCookieRemove(FilterCookieFileEvent $filterEvent)
    {
        throw new \Exception('TODO!');
        if (file_exists($filename = $filterEvent->getCookieFile())) {
            unlink($filename);
        }
    }

    /**
     * Set cookie filename
     *
     * @param string $filename
     */
    public function setFilename($filename)
    {
        $this->filename = (string) $filename;
    }

    /**
     * Copy cookie in database
     *
     * @param string $filename
     * @return boolean True on success
     */
    public function copyCookie($filename)
    {
        throw new \Exception('TODO!');
        if (null === $this->path) {
            return false;
        }
        copy($this->path, dirname($this->path) . '/' . $filename);
        return true;
    }

    /**
     * Get list of subscribed events
     *
     * @return array
     */
    public static function getSubscribedEvents()
    {
        return array(
            CookieFileEvent::LOAD => 'onCookieLoad',
            CookieFileEvent::REMOVE => 'onCookieRemove',
            CookieFileEvent::SHUTDOWN => 'onCookieRemove',
        );
    }

}
