<?php  // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2014 hipplay Inc.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF hipplay Inc.
# The copyright notice above does not evidence any actual or intended
# publication of such source code. The contents of this file may not
# be disclosed to third parties, copied or duplicated in any form, in
# whole or in part, without the prior written permission of
# hipplay Inc.
#
namespace HipPlayConnect\REST\services\sessions;


use DOMDocument;
use DOMElement;
use HipPlayConnect\Identity\AxSession;
use HipPlayConnect\REST\AxAbstractRESTResource;
use HipPlayConnect\REST\AxRESTController;
use HipPlayConnect\REST\AxRESTResourceInterface;
use HipPlayConnect\REST\AxRESTResponse;

/**
 * Class AxSessionRESTResource
 *
 * @package HipPlayConnect\REST\services\sessions
 *
 * !!! Works only for the current session !!!
 */
class AxSessionRESTResource extends AxAbstractRESTResource implements AxRESTResourceInterface
{
    protected $closeSession = false;
	protected $session_id; // not used in practice
	
	public function __construct( $session_id ) {
		$this->session_id = $session_id; // not used in practice
	}
        
	public function DELETE( array $queryParams = array() )
	{	   
	   	// TODO: put back the test on session
	   	// To do so, we need to return the session id once the user is logged in so that it can use the right session id in the future
	   	
	    // log out if logged in; silently skip that step otherwise
	    if ( ( AxSession::isLoggedIn() ) /* && session_id() == $this->session_id */ )
	    {
            AxSession::logUserOut();
	    }
 
    	// return the anonymous visitor XML in case the user is staying in the app
		return new AxRESTResponse(
		    200,
		    self::getLoggedOutXml(),
       		'text/xml; charset=UTF-8'
		);
	}

    private function getLoggedOutXml() {
        $mDoc = new DOMDocument( '1.0' );
        /** @var DOMElement $mUserNode */
        $mUserNode = $mDoc->appendChild( $mDoc->createElement( 'user' ) );

        $mUserNode->setAttribute( 'href', AxRESTController::URI_PREFIX . 'accounts/anonymous' );
        $mUserNode->setAttribute( 'username', '' );
        $mUserNode->setAttribute( 'isAdmin', 'false' );
        $mUserNode->setAttribute( 'isGuest', 'true' );
        $mUserNode->setAttribute( 'isHipServUser', 'false' );
        $mUserNode->setAttribute( 'isFamilyMember', 'false' );

//        $mLocaleSetting = AxUser::getDefaultLocaleSetting();
//        $mLocaleSetting->permission = '';
//        $mUserNode->appendChild( AxPreference::getXMLSettings( 'session', array( $mLocaleSetting ), $mDoc ) );

        return $mDoc->saveXML();
    }
}