// step4.cpp : Defines the initialization routines for the DLL.
//

#include "stdafx.h"
#include "step4.h"
#include <ldefin2d.h>

#ifdef __LIGHT_VERSION__
#include <klAPI5.h>
#else
#include <kAPI5.h>
#endif

#include <ksConstants.h>

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

//
//	Note!
//
//		If this DLL is dynamically linked against the MFC
//		DLLs, any functions exported from this DLL which
//		call into MFC must have the AFX_MANAGE_STATE macro
//		added at the very beginning of the function.
//
//		For example:
//
//		extern "C" BOOL PASCAL EXPORT ExportedFunction()
//		{
//			AFX_MANAGE_STATE(AfxGetStaticModuleState());
//			// normal function body here
//		}
//
//		It is very important that this macro appear in each
//		function, prior to any calls into MFC.  This means that
//		it must appear as the first statement within the 
//		function, even before any object variable declarations
//		as their constructors may generate calls into the MFC
//		DLL.
//
//		Please see MFC Technical Notes 33 and 58 for additional
//		details.
//

/////////////////////////////////////////////////////////////////////////////
// CStep4App

BEGIN_MESSAGE_MAP(CStep4App, CWinApp)
	//{{AFX_MSG_MAP(CStep4App)
		// NOTE - the ClassWizard will add and remove mapping macros here.
		//    DO NOT EDIT what you see in these blocks of generated code!
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()


/////////////////////////////////////////////////////////////////////////////
// CStep4App construction

CStep4App::CStep4App()
{
}

/////////////////////////////////////////////////////////////////////////////
// The one and only CStep4App object

CStep4App theApp;

//-------------------------------------------------------------------------------
//
// ---
unsigned int WINAPI LIBRARYID(){
	return IDR_LIBID;
}

KompasObject kompas( NULL );

void DrawTxtDB();
void DrawRectCallBack( ksDocument2D& doc );
void DrawRectNULL( ksDocument2D& doc );
void WriteSlideStep( ksDocument2D& doc );
void TestShowDialog( ksDocument2D& doc );
void WorkRelativePath ();
void WorkSystemPath( ksDocument2D& doc );

//-------------------------------------------------------------------------------
//
// ---
void GetKompas() {
	if ( !kompas.m_lpDispatch ) {
		CString filename;
		if( ::GetModuleFileName(NULL, filename.GetBuffer(255), 255) ) {
			filename.ReleaseBuffer( 255 );
			CString libname;

      #ifdef __LIGHT_VERSION__
        libname.LoadString( IDS_STRING5 );  //klAPI5.dll
      #else
        libname.LoadString( IDS_STRING4 );  //kAPI5.dll
      #endif

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

			HINSTANCE hAppAuto = LoadLibrary( filename ); //  kAPI5.dll
			if(  hAppAuto ) {
				typedef LPDISPATCH ( WINAPI *FCreateKompasObject )(); 
				FCreateKompasObject pCreateKompasObject = 
					(FCreateKompasObject)GetProcAddress( hAppAuto, "CreateKompasObject" );	
				if ( pCreateKompasObject ) 
					kompas = pCreateKompasObject();
				FreeLibrary( hAppAuto );
			}
		}
	}
}

//-------------------------------------------------------------------------------
//
// ---
void WINAPI LIBRARYENTRY( unsigned int comm ) {
	//      .exe ,     
	//   dll   define
	AFX_MANAGE_STATE(AfxGetStaticModuleState());

	GetKompas();
	if ( kompas.m_lpDispatch ) {
		switch ( comm ) {
			case 1  : ::DrawTxtDB();      break; //   
			case 3  : {                                     //   
					long h1;
					if ( kompas.ksReadInt(" ", 10000, -100000l, 100000l, &h1) ) { 
						char buf[20];
						::sprintf( buf, "h = %ld", h1 );
						kompas.ksMessage( buf );
					}
					else 
						kompas.ksMessage( "" );
				}
				break; 
			case 4  : {  //   
					CString name( kompas.ksChoiceFile("*.cdw", NULL, true) );
					if ( !name.IsEmpty() ) 
						kompas.ksMessage( name );
					else 
						kompas.ksMessage( "" );
				}
				break; 
			case 9  : ::WorkRelativePath();				 break; //     
			default :
				ksDocument2D doc( kompas.ActiveDocument2D() );
				if ( doc.m_lpDispatch && doc.GetReference() ) {
					switch ( comm ) {
						case 2  : {
								if ( kompas.ksYesNo("  CallBack?") )
									DrawRectCallBack( doc );
								else
									DrawRectNULL( doc );
							}
							break; //  
						case 6  : ::WriteSlideStep( doc );			break; //    
						case 7  : ::TestShowDialog( doc );      break; //   (    step4_3.cpp )
						case 8  : {
								kompas.ksEnableTaskAccess( 0 ); //   
								for ( int i = 0; i < 10000; i++ ) {
									doc.ksLineSeg( 10, 10 + i, 20, 10 + i, 1 );
									if ( !(i % 100) ) {
										//     
										//      
										::PostThreadMessage( ::GetCurrentThreadId(), 0, 0, 0 );
										kompas.ksPumpWaitingMessages(); //   100    
																										//   Windows    
																										// ,     
									}
								}
								kompas.ksEnableTaskAccess( 1 ); //   
							}
							break; 
						case 10 : ::WorkSystemPath( doc );	   break; //    
					}
				}
		}
	}
}


//-------------------------------------------------------------------------------
//
// ---
void DrawTxtDB() {


  reference bd, r1, r2, r3;
  int i = 1;
  struct {
    double dr, l;
    int f;
  } b;
  char buf[128];
	ksDataBaseObject data( kompas.DataBaseObject() );
  ksUserParam par( kompas.GetParamStruct(ko_UserParam) );
  ksLtVariant item( kompas.GetParamStruct(ko_LtVariant) );
	ksDynamicArray arr( kompas.GetDynamicArray(LTVARIANT_ARR) );
  if ( !par.m_lpDispatch || !item.m_lpDispatch || !data.m_lpDispatch ) 
		return;
	par.Init();
	par.SetUserArray( arr );
	item.Init();
	  item.SetDoubleVal( 0 );
	  arr.ksAddArrayItem( -1, item );
	item.Init();
  	item.SetDoubleVal( 0 );
		arr.ksAddArrayItem( -1, item );
  item.Init();
	  item.SetIntVal(0);
	  arr.ksAddArrayItem( -1, item );

	char libName[255];
	::strcpy( libName, kompas.ksChoiceFile( "*.loa"," (*.loa)|*.loa|  (*.*)|*.*|", 1 ) );
  if( libName ) { 
    bd = data.ksCreateDB("TXT_DB"); // ,   
    if (data.ksConnectDB(  bd, libName) ){ //      (    -   )
      r1 = data.ksRelation( bd ); //  -      
        data.ksRDouble( "dr" );//   ,
        data.ksRDouble( "L" ); //      
				data.ksRInt ("");
      data.ksEndRelation();

      //  -    (   
      //     )
      data.ksDoStatement( bd, r1, "1 2 3" ); // dr - 1, L - 2,   -3
      while( i ) {
        i= data.ksReadRecord( bd, r1, par ); //        b
        if ( i ) {
  					arr.ksGetArrayItem( 0, item );
						b.dr = item.GetDoubleVal();
	  				arr.ksGetArrayItem( 1, item );
						b.l = item.GetDoubleVal();
	  				arr.ksGetArrayItem( 2, item );
						b.f = item.GetIntVal();
          ::sprintf( buf, "DR = %g\nL = %g\nF = %d", b.dr, b.l, b.f );//item.GetDoubleVal(), item1.GetDoubleVal(), item2.GetIntVal());
          kompas.ksMessage( buf);
        }
      }
      kompas.ksMessage( "end");

			i = 1;
/*			par.Init();
	    par.SetUserArray( arr );*/
			arr.ksClearArray();
      item.Init();
	      item.SetStrVal("");
			  arr.ksAddArrayItem( -1, item );
      r2 = data.ksRelation( bd ); //  -      
 				data.ksRChar( "", 255, 0 );
      data.ksEndRelation();

      data.ksDoStatement( bd, r2, "2" );//  -    (   
      while( i ) {
        i= data.ksReadRecord( bd, r2, par ); //        b
        if ( i ) {
 					arr.ksGetArrayItem( 0, item );
					::sprintf( buf, "L = %s", item.GetStrVal() );
					kompas.ksMessage( buf );
					//kompas.ksMessage( item.GetStrVal() );
        }
      }
      kompas.ksMessage( "end");

			struct {
				double a, l;
			}con;
			i = 1;

			arr.ksClearArray();
      item.Init();
	      item.SetDoubleVal(0);
			  arr.ksAddArrayItem( -1, item );
      item.Init();
	      item.SetDoubleVal(0);
			  arr.ksAddArrayItem( -1, item );
      r3 = data.ksRelation( bd ); //  -      
 				data.ksRDouble("");
				data.ksRDouble("L");
      data.ksEndRelation();

      data.ksDoStatement( bd, r3, "1 2" );//  -    (   
			data.ksCondition( bd, r3, "L=100||L=150" );
      while( i ) {
        i= data.ksReadRecord( bd, r3, par ); //        b
        if ( i ) {
 					arr.ksGetArrayItem( 0, item );
          con.a = item.GetDoubleVal();
					arr.ksGetArrayItem( 1, item );
					con.l = item.GetDoubleVal();
					::sprintf( buf, "dr = %g\nL = %g", con.a, con.l );
					kompas.ksMessage( buf );
        }
      }
      kompas.ksMessage( "end");
    }
    data.ksDeleteDB( bd ); // ,   
  }
}

//-------------------------------------------------------------------------------
//
// ---
void WriteSlideStep( ksDocument2D& doc ) {
  //   
  CString name( kompas.ksSaveFile("*.rc", NULL, NULL, false) );
	if ( !name.IsEmpty() ) {
	  ksRequestInfo info( kompas.GetParamStruct(ko_RequestInfo) );
		if ( info.m_lpDispatch ) {
			info.Init();
			info.SetCommandsString( "   " );
	    //    -      
		  double x, y;
			if ( doc.ksCursor(info, &x, &y, NULL) ) {
				long slideID;
				if ( kompas.ksReadInt("  ", 100, 0, 32000, &slideID) ) {
					if ( !kompas.ksWriteSlide(name, slideID, x,  y) )
						kompas.ksError( "  " );
					doc.ksClearGroup( 0, true );
				}
      }
    }
  }
}

//---------------------------------------------------------------------------------
//     
//----------------------------------------------------------------------------------
void  WorkRelativePath() {
  //  
	CString mainName( kompas.ksChoiceFile("*.*", "  (*.*)|*.*|", true) );
	CString fileName( kompas.ksChoiceFile("*.*", "  (*.*)|*.*|", true) );
	if ( !mainName.IsEmpty() && !fileName.IsEmpty() ) {
    //  
		CString relName( kompas.ksGetRelativePathFromFullPath(mainName,    //     
																													fileName) ); //     

		CString mess( "  : " );
		mess += mainName;
    mess += " \n";
    mess += "  : ";
    mess += fileName ;
    mess += " \n";
    mess += "  : ";
    mess += relName ;
		kompas.ksMessage( mess );

    //  
		CString fullName( kompas.ksGetFullPathFromRelativePath(mainName,   //     
																													 relName) ); //     (        )
    mess = "  : ";
    mess +=  mainName;
    mess += " \n";
    mess += "  : ";
    mess += relName ;
    mess += " \n";
    mess += "  : ";
    mess += fullName;
    mess += " \n";
		kompas.ksMessage( mess );
	}
}

//---------------------------------------------------------------------------------
//    
//----------------------------------------------------------------------------------
void  WorkSystemPath( ksDocument2D& doc ) {
  char* catalogName[] = { "  ", 
                          " "       ,
                          "  ", 
                          " "   ,
                          "INI-" };
  //       
  ksRequestInfo info( kompas.GetParamStruct(ko_RequestInfo) );
	if ( info.m_lpDispatch ) {
		info.Init();
		info.SetTitle( "  " );
		info.SetCommandsString( "! ! ! ! !INI- " );
		info.SetPrompt( "  " );
		int j;
		static char* buf = "user.ttt";
		CString fileName;
		int typeCatalog;
		do {
			j = doc.ksCommandWindow( info );
			if ( j > 0 ) {
				switch ( j ) {
					case 1 : typeCatalog = sptSYSTEM_FILES; break; //    
					case 2 : typeCatalog = sptLIBS_FILES  ; break; //    
					case 3 : typeCatalog = sptTEMP_FILES  ; break; //     
					case 4 : typeCatalog = sptCONFIG_FILES; break; //     
					case 5 : typeCatalog = sptINI_FILE    ; break; //    INI- 
				}
				// 
				fileName = kompas.ksGetFullPathFromSystemPath( buf,           //    (    )
																		                   typeCatalog ); //    . ksSystemPath
				CString mess( "    user.ttt \n" );
				mess +=  catalogName[j - 1];
				mess += " :\n";
				mess += fileName ;
				kompas.ksMessage( mess );

				// 
				CString relName( kompas.ksGetRelativePathFromSystemPath(fileName,       //    
																		                            typeCatalog) ); //    . ksSystemPath
				mess = "    \n";
				mess += fileName;  
				mess += "\n";
				mess +=  catalogName[j -1];
				mess += " :\n";
				mess += relName;
				kompas.ksMessage( mess );
         
			}
		} while ( j > 0 );
	}
}
