////////////////////////////////////////////////////////////////////////////////
//
// step1.cpp -          OpenGL
// TestDocumentFrameNotify        -    
// TestCurrentDocumentFrameNotify -    
// 
////////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include <afxdllx.h> 

#include "resource.h"

#ifndef _ABASEEVENT_H
#include "abaseEvent.h"
#endif

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

//-------------------------------------------------------------------------------
//       DLL
// ---
static AFX_EXTENSION_MODULE StepDLL = { NULL, NULL };

IApplicationPtr newKompasAPI;            //  Application 7     

void TestDocumentFrameNotify();          //    
void TestCurrentDocumentFrameNotify( int redrawType );


extern cBaseEvent * NewDocumentFrameEvent( IDocumentFrame* documentFrame, reference doc, int redrawType = 0 );

//-------------------------------------------------------------------------------
//   
//    DLL
// ---
extern "C" int APIENTRY
DllMain( HINSTANCE hInstance, DWORD dwReason, LPVOID lpReserved )
{
  UNREFERENCED_PARAMETER( lpReserved );

  if ( dwReason == DLL_PROCESS_ATTACH )
  {
    TRACE0( "DLL Initializing!" );
 
    if ( !AfxInitExtensionModule( StepDLL, hInstance ) )
      return 0;

    new CDynLinkLibrary( StepDLL );
  }
  else if ( dwReason == DLL_PROCESS_DETACH )
  {
    cBaseEvent::TerminateEvents();
    cBaseEvent::DestroyList();
    if ( newKompasAPI )
      newKompasAPI = NULL;
    TRACE0( "DLL Terminating!" );
    AfxTermExtensionModule( StepDLL );
  }
  return 1;
}


//-------------------------------------------------------------------------------
//
// ---
CString _LoadStr( int id )
{
  TCHAR buf[255];
  LoadString( StepDLL.hModule, id, buf, 255 );
  return buf;
}


//----------------------------------------------------------------------------------------------
//     
//---
LPTSTR LoadStr( int ID ) {
  static TCHAR buf[255];
  ksConvertLangStrExT( StepDLL.hModule, ID, buf, 255 );
  return buf;
}


//-------------------------------------------------------------------------------
//     API
// ---
void GetNewKompasAPI() {
	if ( !( IApplication* )newKompasAPI ) {
		CString filename;
		if( ::GetModuleFileName(NULL, filename.GetBuffer(255), 255) ) {
			filename.ReleaseBuffer( 255 );
			CString libname;

      #ifdef __LIGHT_VERSION__
        libname = _LoadStr( IDS_API7LT );  // klAPI7.dll
      #else
        libname = _LoadStr( IDS_API7 );    // kAPI7.dll
      #endif

			filename.Replace( filename.Right(filename.GetLength() - (filename.ReverseFind(_T('\\')) + 1)), 
												libname );

			HINSTANCE hAppAuto = LoadLibrary( filename ); //  kAPI7.dll
			if(  hAppAuto ) {
				//      KompasApplication  
        typedef LPDISPATCH ( WINAPI *FCreateKompasApplication )(); 
				 
        FCreateKompasApplication pCreateKompasApplication = 
					(FCreateKompasApplication)GetProcAddress( hAppAuto, "CreateKompasApplication" );	
				if ( pCreateKompasApplication )
					newKompasAPI = IDispatchPtr( pCreateKompasApplication(), false/*AddRef*/ ); //   Application
				FreeLibrary( hAppAuto );  
			}
		}
	}
}


//------------------------------------------------------------------------------
//  
// ---
int LibMessage( LPCTSTR str, int flags = MB_OK ) {
  int res = 0;

  if ( str && str[0] ) {                  //  
    int enabse = ::IsEnableTaskAccess();  //  
    if ( enabse )                         //     
      ::EnableTaskAccess(0);              //  

    //                                      
    res = MessageBox( (HWND) GetHWindow(), str, LoadStr(IDR_LIB), flags );

    if ( enabse )                         //      
      ::EnableTaskAccess(1);              //    
  }

  return res;
}

//------------------------------------------------------------------------------
//  
// ---
int LibMessage( int strId, int flags = MB_OK ) {
  return ::LibMessage( LoadStr(strId), flags );
}

//-------------------------------------------------------------------------------
//   
// ---
int WINAPI LIBRARYID()
{
  return IDR_LIB;
}


//-------------------------------------------------------------------------------
//   
// ---
void WINAPI LIBRARYENTRY( unsigned int comm )
{
  //   
  switch ( comm ) 
  {       
    case 1 :
      TestDocumentFrameNotify();
      break;
    case 2 :
    case 3 :
    case 4 :
    case 5 :
      TestCurrentDocumentFrameNotify( comm - 2 ); //    
      break;
  }
}


//-------------------------------------------------------------------------------
//  ,   
// ---
BOOL CreateExtrusion( IPartPtr& part )
{
  BOOL res = FALSE;
  //   
  IEntityPtr entitySketch( part->NewEntity( o3d_sketch ), false /*AddRef*/ );
  if ( entitySketch )
  {
    //        
    ISketchDefinitionPtr sketchDefinition( IUnknownPtr( entitySketch->GetDefinition(), false/*AddRef*/ ) );
    if ( sketchDefinition )
    {
      //     XOY
      IEntityPtr basePlane( part->GetDefaultEntity( o3d_planeXOY ), false /*AddRef*/ );
 
      //   
      sketchDefinition->SetPlane( basePlane ); //   XOY   
      sketchDefinition->SetAngle( 45 );        //   
 
      //  
      entitySketch->Create();

      //     
      if ( sketchDefinition->BeginEdit() )
      {
        //    - 
        LineSeg(  50,  50, -50,  50, 1 );
        LineSeg(  50, -50, -50, -50, 1 );
        LineSeg(  50, -50,  50,  50, 1 );
        LineSeg( -50, -50, -50,  50, 1 );
        //     
        sketchDefinition->EndEdit();
      }

      //  
      IEntityPtr entityExtrusion( part->NewEntity( o3d_baseExtrusion ), false /*AddRef*/ );
      if ( entityExtrusion )
      {
        //    
        IBaseExtrusionDefinitionPtr extrusionDefinition( IUnknownPtr( entityExtrusion->GetDefinition(), false/*AddRef*/ ) );
        if ( extrusionDefinition )
        {
          //    
          extrusionDefinition->SetDirectionType( dtNormal );     //   ( dtNormal	- 
                                                                 // ,    - ,
                                                                 // dtReverse	-  ,    - 
                                                                 // dtBoth -   , dtMiddlePlane    )
          //      
          extrusionDefinition->SetSideParam( true,               //   ( TRUE -  ,
                                                                 // FALSE -   )
                                             etBlind,            //   ( etBlind -   ,
                                                                 // etThroughAll -   , etUpToVertexTo -    ,
                                                                 // etUpToVertexFrom -    , etUpToSurfaceTo - 
                                                                 //   , etUpToSurfaceFrom -    ,
                                                                 // etUpToNearSurface	-    )
                                             100,                //  
                                             0,                  //  
                                             true );             //   ( TRUE -  , FALSE -   )
          //    
          extrusionDefinition->SetThinParam( false,              //   
                                             dtBoth,             //    
                                             10,                 //     
                                             10 );               //     
          extrusionDefinition->SetSketch( entitySketch );        //   
          entityExtrusion->SetName( _bstr_t(_T(" - ")) );

          //   
          res = !!entityExtrusion->Create();
        }
      }
    }
  }
  return res;
}

//-----------------------------------------------------------------------------
//
// ---
void TestDocumentFrameNotify() {
  IDocument3DPtr doc3D( ksGet3dDocument(), false/*AddRef*/ );
  if ( doc3D ) {
    doc3D->Create( FALSE, 1 ); //   
    doc3D->SetDrawMode( vm_Shaded );
    doc3D->SetShadedWireframe( TRUE );
    IPartPtr part( doc3D->GetPart( pTop_Part ), false/*AddRef*/ );
    if ( part ) {
      if ( CreateExtrusion( part ) ) {
        part->SetName( _bstr_t(_T("")) );
        part->Update();
        GetNewKompasAPI();
        if ( newKompasAPI ) {
          
          IKompasDocumentPtr komDoc( newKompasAPI->GetActiveDocument() );
          if ( komDoc ) {
            IDocumentFramesPtr docFrames( komDoc->GetDocumentFrames() );
            if ( docFrames ) {
              IDocumentFramePtr documentFrame( docFrames->GetItem( _variant_t( (long)0 ) ) );
              if ( documentFrame ) {
	              NewDocumentFrameEvent( documentFrame, komDoc->GetReference() );
                documentFrame->SetGabaritModifying();
                documentFrame->RefreshWindow();
              }
            }
          }
        }
      }
    }
  }
}


//-----------------------------------------------------------------------------
//
// ---
void TestCurrentDocumentFrameNotify( int redrawType ) 
{
  GetNewKompasAPI();
  if ( newKompasAPI ) {
    
    IKompasDocumentPtr komDoc( newKompasAPI->GetActiveDocument() );
    if ( komDoc ) {
      IDocumentFramesPtr docFrames( komDoc->GetDocumentFrames() );
      if ( docFrames ) {
        IDocumentFramePtr documentFrame( docFrames->GetItem( _variant_t( (long)0 ) ) );
        if ( documentFrame ) {
	        NewDocumentFrameEvent( documentFrame, komDoc->GetReference(), redrawType );
          documentFrame->SetGabaritModifying();
          documentFrame->RefreshWindow();
        }
      }
    }
  }
}
