#include "StdAfx.h"
#include "SKOKO.h"
#include "FileAttrUpdate.h"

//
// CChangeOwner
//
CChangeOwner::CChangeOwner(
  const BGDNet::Context& ctx,
  const char* curOwner,
  const char* newOwner ) :
    m_ctx(ctx),
    m_curOwner(curOwner),
    m_newOwner(newOwner)
{
  m_curOwner.AnsiToOem();
  m_newOwner.AnsiToOem();
}

bool CChangeOwner::updateAttributes( BGDNet::File* pFile )
{
  bool changeOwner = false;
  if (m_curOwner.IsEmpty())
    changeOwner = true;
  else
  {
    nuint32 curOwnerId = pFile->ownerId();
    try
    {
      BGDNet::NDSObject(
        m_ctx,
        pFile->vol()->srv()->objNameById(curOwnerId, m_ctx));
    }
    catch (const BGDNet::Exception&)
    {
      curOwnerId = 0;
    }
    if (m_curOwner == UNKNOWN_OWNER && !curOwnerId)
      changeOwner = true;
    else
    {
      const nuint32 searchOwnerId = pFile->vol()->srv()->objIdByName(
        m_curOwner,
        m_ctx);
      changeOwner = (searchOwnerId == curOwnerId);
    }
  }

  if (changeOwner)
    pFile->ownerName(m_ctx, m_newOwner);

  return changeOwner;
}

//
// CRepairOwnerModifier
//
CRepairOwnerModifier::CRepairOwnerModifier( const BGDNet::Context& ctx ) :
  m_ctx(ctx)
{
}

bool CRepairOwnerModifier::updateAttributes( BGDNet::File* pFile )
{
  nuint32 ownerId = 0;
  nuint32 modifierId = 0;
  
  // Проверяем "owner"-а:
  try
  {
    BGDNet::NDSObject user(m_ctx, pFile->ownerName(m_ctx));
    CString ownerName = user.dn();
    ownerName.OemToAnsi();
    ownerId = theApp.IsAdmin(ownerName) ? 0 : pFile->ownerId();
  }
  catch (const BGDNet::Exception&)
  {
    ownerId = 0;
  }

  // Проверяем "modifier"-а:
  try
  {
    BGDNet::NDSObject user(m_ctx, pFile->modifierName(m_ctx));
    CString modifierName = user.dn();
    modifierName.OemToAnsi();
    modifierId = theApp.IsAdmin(modifierName) ? 0 : pFile->modifierId();
  }
  catch (const BGDNet::Exception&)
  {
    modifierId = 0;
  }

  if (!ownerId && !modifierId)
    return false;

  if (!ownerId)
    pFile->ownerId(modifierId);
  else if (!modifierId)
    pFile->modifierId(ownerId);

  return (!ownerId || !modifierId);
}
