<?php
/********************************************************************************
 * (c)1337 aheadware.com - All rights reserved
 ********************************************************************************/


class TB_Server_Core_Session {

    // Singleton
    private function __construct() {}
    private function __clone() {}
    private static $instance = NULL;

    // Members
    /** @var TB_Shared_Ent_Core_Session $session  */
    private $session = NULL;

    public static function get() {
        if ( is_null( self::$instance ) ) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    /**
     * Creates unique session token
     *
     * @return string
     */
    public static function generateToken() {
        return uniqid();
    }

    /**
     * Init singleton with current session entity
     *
     * @param TB_Shared_Ent_Core_Session $session
     */
    public function init( TB_Shared_Ent_Core_Session $session ) {
        $this->session = $session;
    }

    /**
     * Destorys current session
     *
     * @todo - What should we do exactly here?
     */
    public function destory() {
        $this->session = NULL;
        // @todo - what else?
    }

    /**
     * @return bool
     */
    public function isInitialized() {
        return ( isset( $this->session ) );
    }

    /**
     * Get token of current session
     *
     * @return string
     */
    public function getToken() {
        return $this->session->token;
    }

    /**
     * @return NULL|TB_Shared_Ent_TeamData_Profile
     */
    public function getProfile() {
        return TB_Shared_Ent_TeamData_Profile::get( $this->session->profile_id );
    }

    /**
     * Get account from current session
     *
     * @return NULL|TB_Shared_Ent_Core_Account
     */
    public function getAccount() {
        if ( isset( $this->session ) ) {
            return TB_Shared_Ent_Core_Account::get( $this->session->account_id );
        } else {
            return NULL;
        }
    }

    /**
     * Get team from session profile
     *
     * @return NULL|TB_Shared_Ent_TeamData_Team
     */
    public function getTeam() {
        $profile = $this->getProfile();
        if ( isset( $profile ) ) {
            return TB_Shared_Ent_TeamData_Team::get( $profile->team_id );
        } else {
            return NULL;
        }
    }

    /**
     * @return bool
     */
    public function isPremium()
    {
        /** @var TB_Shared_Ent_TeamData_Team $team */
        $team = $this->getTeam();

        if ( is_null( $team ) )
        {
            return false;
        }
        else
        {
            return $team->isPremium();
        }
    }

    /**
     * Returns the original DB session row entity
     *
     * @return TB_Shared_Ent_Core_Session
     */
    public function getEntCoreSession() {
        return $this->session;
    }
}