/*

    ========== licence begin  GPL
    Copyright (c) 2005 SAP AG

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation; either version 2
    of the License, or (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
    ========== licence end

*/
#include "Oms/OMS_CriticalSection.hpp"
#include "Oms/OMS_Session.hpp"
#include "Oms/OMS_Handle.hpp"
#include "Oms/OMS_ObjectContainer.hpp"

/*----------------------------------------------------------------------*/
/* Implementation of class OmsCriticalSection                           */
/*----------------------------------------------------------------------*/

OmsCriticalSection::OmsCriticalSection(OmsHandle* h, int regionId) 
  : m_session(h->m_pSession), m_inSection(false), 
    m_regionId(regionId + OMS_INTERNAL_CRITICAL_SECTIONS)
{
  if ((regionId < 0) || !(m_regionId < OMS_Globals::KernelInterfaceInstance->GetOmsRegionCnt())) // PTS 1112197
  {
    h->dbpOpError("OmsCriticalSection : invalid regionId %d", regionId); 
    m_session->ThrowDBError (e_invalid_csid, "OmsCriticalSection", __MY_FILE__, __LINE__);
  }
}

/*----------------------------------------------------------------------*/

void OmsCriticalSection::omsEnter() {
  if ((m_inSection) || (m_session->m_critical_section_in_use[m_regionId-OMS_INTERNAL_CRITICAL_SECTIONS])) {
    m_session->ThrowDBError (e_already_in_critical_section, "omsEnter", __MY_FILE__, __LINE__);
  }
  m_session->m_critical_section_in_use[m_regionId-OMS_INTERNAL_CRITICAL_SECTIONS] = true;
  m_session->m_lcSink->EnterCriticalSection(m_regionId);
  m_inSection = true;
}

/*----------------------------------------------------------------------*/

void OmsCriticalSection::omsLeave() {
  if (m_inSection) {
    m_session->m_lcSink->LeaveCriticalSection(m_regionId);
    m_session->m_critical_section_in_use[m_regionId-OMS_INTERNAL_CRITICAL_SECTIONS] = false;
    m_inSection = false;
  }
  else {
    m_session->ThrowDBError ( e_not_in_critical_section, "omsLeave", __MY_FILE__, __LINE__);
  }
}

/*----------------------------------------------------------------------*/

OmsCriticalSection::~OmsCriticalSection() {
  if (m_inSection) {
    omsLeave();
  }
}

