// MainFrm.cpp : implementation of the CMainFrame class
//

#include "stdafx.h"
#include "MW4GameEd2.h"

#include "MainFrm.h"
#include "OverviewWindow.h"
#include "ObjectManager.h"
#include "ObjManFrame.h"
#include "GUIPath.h"
#include "Refresher.h"
#include "ResourceDlg.h"
#include "GameFrame.h"
#include "OpenMissionDlg.h"
#include "NewMissionDlg.h"
#include "CameraSettings.h"
#include "CameraController.h"
#include "ProgTimeDlg.h"
#include "OverFrame.h"
#include "SaveAsDlg.h"
#include "MapManagerdlg.h"
#include "AudioFileDlg.h"
#include "GameFrame.h"
#include "OverviewProperties.h"
#include "MissionReportDlg.h"
#include "MissionReport.h"
#include "BatchReportDlg.h"
#include <Buildnum\BuildNum.h>



#include "GameInterface.h"

extern bool gHideWindows;

/////////////////////////////////////////////////////////////////////////////
// CMainFrame

//IMPLEMENT_DYNAMIC(CMainFrame, CMDIFrameWnd)

BEGIN_MESSAGE_MAP(CMainFrame, CMDIFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
ON_COMMAND(ID_FILE_OPEN, OnFileOpen)
ON_COMMAND(ID_FILE_SAVE, OnFileSave)
ON_WM_CLOSE()
ON_COMMAND(ID_WINDOWS_GAMEWINDOW, OnWindowsGamewindow)
ON_COMMAND(ID_WINDOWS_INSTANCEWINDOW, OnWindowsInstancewindow)
ON_COMMAND(ID_WINDOWS_OVERVIEWWINDOW, OnWindowsOverviewwindow)
ON_COMMAND(ID_WINDOWS_RESOURCEWINDOW, OnWindowsResourcewindow)
ON_COMMAND(ID_WINDOWS_CAMERASETTINGS, OnWindowsCameraSettings)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_GAMEWINDOW, OnUpdateWindowsGamewindow)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_OVERVIEWWINDOW, OnUpdateWindowsOverviewwindow)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_RESOURCEWINDOW, OnUpdateWindowsResourcewindow)
	ON_COMMAND(ID_TOOLS_CHECKSCRIPTS, OnToolsCheckscripts)
ON_COMMAND(ID_FILE_NEW, OnFileNew)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_CAMERASETTINGS, OnUpdateWindowsCamerasettings)
ON_COMMAND(ID_WINDOWS_RESETWINDOWS, OnWindowsResetwindows)
ON_UPDATE_COMMAND_UI(ID_OPTIONS_CAMERAANIMATIONFOROBJECTPLACEMENT, OnUpdateOptionsAnimatedCamera)
ON_COMMAND(ID_OPTIONS_CAMERAANIMATIONFOROBJECTPLACEMENT, OnOptionsAnimatedCamera)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_INSTANCEWINDOW, OnUpdateWindowsInstancewindow)
ON_COMMAND(ID_FILE_SAVEAS, OnFileSaveas)
ON_COMMAND(ID_FILE_MAPMANAGER, OnFileMapmanager)
ON_COMMAND(ID_WINDOWS_OVERVIEWPROPERTIES, OnWindowsOverviewproperties)
ON_UPDATE_COMMAND_UI(ID_WINDOWS_OVERVIEWPROPERTIES, OnUpdateWindowsOverviewproperties)
ON_COMMAND(ID_FILE_AUDIOFILE, OnFileAudiofile)
ON_COMMAND(ID_OPTIONS_MISSIONREPORT, OnOptionsMissionreport)
ON_COMMAND(ID_OPTIONS_BATCHREPORTS, OnOptionsBatchreports)
	ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateFileSave)
	ON_UPDATE_COMMAND_UI(ID_FILE_SAVEAS, OnUpdateFileSaveas)
	ON_UPDATE_COMMAND_UI(ID_OPTIONS_MISSIONREPORT, OnUpdateOptionsMissionreport)
	ON_COMMAND(ID_OPTIONS_CAMERA_SETTINGS, OnOptionsCameraSettings)
	ON_COMMAND(ID_OPTIONS_MISSIONPROPS, OnOptionsMissionprops)
	ON_COMMAND(ID_OPTIONS_OBJECTIVES, OnOptionsObjectives)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

static UINT indicators[] =
{
	ID_SEPARATOR           // status line indicator
};

/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction

CMainFrame::CMainFrame()
: overWin(0)
, ObjManDlg(0)
, ResDlg(0)
, GameWnd(0)
{
	ObjMan=new ObjectManager;
	RegNoSave=false;
	ChildModal=false;
}

CMainFrame::~CMainFrame()
{
	delete Refresher::Instance;
	delete ObjMan;
	//	delete ObjManDlg;
}

int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CMDIFrameWnd::OnCreate(lpCreateStruct) == -1)
		return -1;
	
	if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
		| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
		!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
	{
		TRACE0("Failed to create toolbar\n");
		return -1;      // fail to create
	}
	
	if (!m_wndStatusBar.Create(this) ||
		!m_wndStatusBar.SetIndicators(indicators,
		sizeof(indicators)/sizeof(UINT)))
	{
		TRACE0("Failed to create status bar\n");
		return -1;      // fail to create
	}
	m_wndStatusBar.ShowWindow(SW_HIDE);

	// TODO: Delete these three lines if you don't want the toolbar to
	//  be dockable
	m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
	EnableDocking(CBRS_ALIGN_ANY);
	DockControlBar(&m_wndToolBar);
	CString title;
	GetWindowText(title);
	SetWindowText(title+" - "+ VER_PRODUCTVERSION_STR);
	return 0;
}

BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
	if( !CMDIFrameWnd::PreCreateWindow(cs) )
		return FALSE;
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs
	
	return TRUE;
}

/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics

#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
	CMDIFrameWnd::AssertValid();
}

void CMainFrame::Dump(CDumpContext& dc) const
{
	CMDIFrameWnd::Dump(dc);
}

#endif //_DEBUG

/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers


void CMainFrame::InitSecondaryWindows()
{
	overWin= new COverFrame(ObjMan,this);
	ObjManDlg= new CObjManFrame(ObjMan,this);
	ResDlg= new CResourceDlg(ObjMan,this);
	GameWnd=new CGameFrame(ObjMan,this);
	Refresher::Instance=new Refresher(&(overWin->m_wndView),ObjManDlg,&(GameWnd->m_wndView));
}

void CMainFrame::RefreshAllWindows(CWnd *ignore)
{
	Refresher::Instance->OverviewRefresh();
	if(ignore!=ObjManDlg) ObjManDlg->Refresh();
}

void CMainFrame::InitPostGame()
{
if(!gHideWindows)
	LoadRegistryInfo();

	ObjMan->BuildResources();

if(!gHideWindows)
	RefreshAllWindows();
}

void CMainFrame::OnFileOpen() 
{
	COpenMissionDlg dlg;
	
	if(SaveIfModifedPrompt()) return;


	if(dlg.DoModal()==IDOK)
	{
		GameWnd->m_wndView.DisplayOff=true;
		CloseMission();
		if(!LoadMission(dlg.m_MissionName,dlg.LoadAtNight)) MessageBox("Mission is corrupt and cannot be loaded","Load Error",MB_OK);
		GameWnd->m_wndView.DisplayOff=false;
	}
	
}

bool CMainFrame::LoadMission(CString mission_name,bool night)
{
	GameWnd->m_wndView.DisplayOff=true;
	CProgTimeDlg pdlg;
	pdlg.InitWin(IDS_LOADMISSION,this);
	CString mission_path;
	mission_path.Format("Content\\Missions\\%s\\%s.Instance",mission_name,mission_name);
	if(!ObjMan->OpenMission(mission_path,night))	//Make the Game Load the mission
		return false;
	pdlg.SetPos(25);
	ObjMan->SyncToGame(&(overWin->m_wndView.drawInfo.vinf));
	pdlg.SetPos(50);
	ObjMan->LoadTextInfo();
	ObjMan->LoadNFOFile();
	pdlg.SetPos(75);
	ObjMan->ResetCamera();
	overWin->m_wndView.InitWindow();
	ResDlg->GetGameData();
	GameWnd->m_wndView.DisplayOff=false;
	GameWnd->m_wndView.FixDisplayWindow();
	RefreshAllWindows();	
	pdlg.SetPos(100);
	return true;
}

bool CMainFrame::SaveIfModifedPrompt()
{
	if(ObjMan && ObjMan->IsLoaded() && ObjMan->IsModified())
	{
		CString save_warn,warn;
		save_warn.LoadString(IDS_SAVECHANGES);
		warn.LoadString(IDS_WARNING);
		if (MessageBox(save_warn,warn,MB_ICONQUESTION | MB_YESNO) == IDNO)
			return false;
		if(ObjMan->IsMultiZone())
		{
			MessageBox("The are MultiZone Objects in this mission please Resolve before saving","Save Error",MB_OK);
			return true;
		}
		ObjMan->SaveMission(true);
	}
return false;	
}

void CMainFrame::OnFileNew() 
{
	if(SaveIfModifedPrompt()) return;
	
	GameWnd->m_wndView.DisplayOff=true;
	CNewMissionDlg dlg;
	if(dlg.DoModal()==IDOK)
	{
		ObjMan->NewMission(dlg.m_MissionName,dlg.m_MapName);
		ObjMan->SyncToGame(&(overWin->m_wndView.drawInfo.vinf));
		ObjMan->ResetCamera();
		overWin->m_wndView.InitWindow();
		ResDlg->GetGameData();
		GameWnd->m_wndView.DisplayOff=true;
		RefreshAllWindows();	
	}
	GameWnd->m_wndView.DisplayOff=false;
	
}

bool CMainFrame::CloseMission()
{
	GameWnd->m_wndView.DisplayOff=true;
	bool res=ObjMan->CloseMission();
	GameWnd->m_wndView.DisplayOff=false;
	return res;
}



void CMainFrame::OnFileSave() 
{
	CProgTimeDlg pdlg;
	pdlg.InitWin(IDS_SAVEMISSION,this);
	if(ObjMan->IsMultiZone())
			MessageBox("The are MultiZone Objects in this mission please Resolve before saving","Save Error",MB_OK);
	else
			ObjMan->SaveMission(true);
}

void CMainFrame::OnClose() 
{
	SaveRegistryInfo();
	if(SaveIfModifedPrompt()) return;
	CloseMission();
	if(NeedResourceBuild) ObjMan->BuildResources();
	CMDIFrameWnd::OnClose();
}


void CMainFrame::ClearRegistryInfo()
{
	RegNoSave=true;
}


void CMainFrame::SaveRegistryInfo()
{
	if(RegNoSave) return;
	
	overWin->SaveToReg();
	ObjMan->SaveToReg();
	ObjManDlg->SaveToReg();
	ResDlg->SaveToReg();
	GameWnd->SaveToReg();
	
}

void CMainFrame::LoadRegistryInfo()
{
	overWin->LoadFromReg();
	ObjMan->LoadFromReg();
	ObjManDlg->LoadFromReg();
	ResDlg->LoadFromReg();
	GameWnd->LoadFromReg();
	
	
}

void CMainFrame::OnWindowsGamewindow() 
{
	GameWnd->ShowWindow(GameWnd->IsWindowVisible()?SW_HIDE:SW_SHOW);	
}

void CMainFrame::OnWindowsInstancewindow() 
{
	ObjManDlg->ShowWindow(ObjManDlg->IsWindowVisible()?SW_HIDE:SW_SHOW);	
}

void CMainFrame::OnWindowsCameraSettings()
{
}

void CMainFrame::OnWindowsOverviewwindow() 
{
	overWin->ShowWindow(overWin->IsWindowVisible()?SW_HIDE:SW_SHOW);	
}

void CMainFrame::OnWindowsResourcewindow() 
{
	ResDlg->ShowWindow(ResDlg->IsWindowVisible()?SW_HIDE:SW_SHOW);	
}


void CMainFrame::OnUpdateWindowsGamewindow(CCmdUI* pCmdUI) 
{
	if (GameWnd != 0)
	{
		pCmdUI->SetCheck(GameWnd->IsWindowVisible());
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
}

void CMainFrame::OnUpdateWindowsInstancewindow(CCmdUI* pCmdUI) 
{
	if (ObjManDlg != 0)
	{
		pCmdUI->SetCheck(ObjManDlg->IsWindowVisible()?1:0);
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
	
}

void CMainFrame::OnUpdateWindowsOverviewwindow(CCmdUI* pCmdUI) 
{
	if (overWin != 0)
	{
		pCmdUI->SetCheck(overWin->IsWindowVisible());
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
}

void CMainFrame::OnUpdateWindowsResourcewindow(CCmdUI* pCmdUI) 
{
	if (ResDlg != 0)
	{
		pCmdUI->SetCheck(ResDlg->IsWindowVisible());
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
}

void CMainFrame::OnUpdateWindowsCamerasettings(CCmdUI* pCmdUI) 
{
}

void CMainFrame::OnUpdateWindowsOverviewproperties(CCmdUI* pCmdUI) 
{
	if (overWin != 0)
	{
		pCmdUI->SetCheck(overWin->m_wndView.m_COverviewProperties->IsWindowVisible());
	}
	else
	{
		pCmdUI->SetCheck(0);
	}
	
}

void CMainFrame::OnWindowsOverviewproperties()
{
	overWin->m_wndView.m_COverviewProperties->ShowWindow(overWin->m_wndView.m_COverviewProperties->IsWindowVisible()?SW_HIDE:SW_SHOW);	
	
}

BOOL CMainFrame::OnIdle()
{
	if(ObjMan->IsLoaded())
	{
		Refresher::Instance->View3DRefresh();
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}


void CMainFrame::OnWindowsResetwindows() 
{
	overWin->ShowWindow(SW_SHOW);
	ObjManDlg->ShowWindow(SW_SHOW);
	ResDlg->ShowWindow(SW_SHOW);
	GameWnd->ShowWindow(SW_SHOW);
	overWin->m_wndView.m_COverviewProperties->ShowWindow(SW_SHOW);
	
	int csize=GetSystemMetrics(SM_CYCAPTION);
	int pos=csize*4;

	overWin->SetWindowPos(NULL,pos,pos,-1,-1,SWP_NOSIZE|SWP_NOZORDER);
	pos+=csize;
	ObjManDlg->SetWindowPos(NULL,pos,pos,-1,-1,SWP_NOSIZE|SWP_NOZORDER);
	pos+=csize;
	ResDlg->SetWindowPos(NULL,pos,pos,-1,-1,SWP_NOSIZE|SWP_NOZORDER);
	pos+=csize;
	GameWnd->SetWindowPos(NULL,pos,pos,-1,-1,SWP_NOSIZE|SWP_NOZORDER);
	pos+=csize;
	overWin->m_wndView.m_COverviewProperties->SetWindowPos(NULL,pos,pos,-1,-1,SWP_NOSIZE|SWP_NOZORDER);
	
}

void CMainFrame::OnUpdateOptionsAnimatedCamera(CCmdUI* pCmdUI) 
{
	if (ObjMan != 0)
	{
		pCmdUI->SetCheck(ObjMan->GetCameraController()->GetLookAtMode()==true?1:0);
	}
}

void CMainFrame::OnOptionsAnimatedCamera() 
{
	if (ObjMan->GetCameraController()->GetLookAtMode() == true)
	{
		ObjMan->GetCameraController()->SetLookAtMode(false);
	}
	else
	{
		if(ObjMan->SelectionCount()>0)
			ObjMan->GetCameraController()->SetLookAtMode(true);
	}
}





void CMainFrame::OnFileSaveas() 
{
	CSaveAsDlg dlg;
	dlg.m_MisName="CopyOf"+ObjMan->GetName();
	if(dlg.DoModal()==IDOK)
	{
		GameWnd->m_wndView.DisplayOff=true;
		if(dlg.m_MisName=="" || dlg.m_MisName.FindOneOf("\"\\.")!=-1)
		{
			CString save_warn,warn;
			save_warn.LoadString(IDS_INVALIDMISNAME);
			warn.LoadString(IDS_ERROR);
			MessageBox(save_warn,warn,MB_OK);
		}
		else
		{
			CProgTimeDlg pdlg;
			pdlg.InitWin(IDS_SAVEMISSION,this);
			if(ObjMan->IsMultiZone())
				MessageBox("The are MultiZone Objects in this mission please Resolve before saving","Save Error",MB_OK);
			else
				ObjMan->SaveMission(dlg.m_MisName,true);
			//	ObjMan->SyncToGame(&(overWin->m_wndView.drawInfo.vinf));
			//	ObjMan->SaveMission(true);
			
		}
		GameWnd->m_wndView.DisplayOff=false;
	}
	
}

void CMainFrame::OnFileMapmanager() 
{
	CMapManagerDlg dlg;
	
	if(dlg.DoModal()==IDOK)
	{
		ObjMan->BuildResources();
	}
	// TODO: Add your command handler code here
	
}



LRESULT CMainFrame::WindowProc(UINT message, WPARAM wParam, LPARAM lParam) 
{
	// TODO: Add your specialized code here and/or call the base class
	MsgHan.Lock();
	if(overWin && ObjManDlg && ResDlg && GameWnd)
	{
		
		if((overWin->InModalState() || ObjManDlg->InModalState() || GameWnd->InModalState()) ) 
		{
			if(!ChildModal) 
			{	
				ChildModal=true;
				BeginModalState(); 
			}
		}
		else	
		{
			if(ChildModal) 
			{
				ChildModal=false;
				EndModalState(); 
			}
		}
	}
	
	LRESULT res=CMDIFrameWnd::WindowProc(message, wParam, lParam);
	MsgHan.Unlock();
	return res;
}

void CMainFrame::OnFileAudiofile() 
{
	if(ObjMan->IsLoaded())
	{
		if(ObjMan->IsModified())
		{
			if (MessageBox("Mission Will be Saved before editing Audio File. OK?","Save Warning",MB_ICONQUESTION | MB_YESNO) == IDNO) return;
			ObjMan->SaveMission(true);
		}
		
		CAudioFileDlg dlg(ObjMan->GetName(),this);
		if(dlg.DoModal()==IDOK)
		{
			if(!LoadMission(ObjMan->GetName(),IsMissionNight())) MessageBox("Error LoadMission","Load Error",MB_OK);
		}
		
	}
}

void CMainFrame::OnOptionsMissionreport() 
{
	if(ObjMan->IsLoaded())
	{
		CMissionReportDlg dlg(this);
		dlg.DoModal();
	}
}

void CMainFrame::OnOptionsBatchreports() 
{
	CBatchReportDlg dlg(this);
	if(dlg.DoModal()==IDOK)
	{
		if(dlg.StringCount>0)
		{
		GameWnd->m_wndView.DisplayOff=true;	
			for(int i=0;i<dlg.StringCount;i++)
			{
				MakeReport(dlg.MissionNames[i],dlg.m_DestPath);
			}	
		GameWnd->m_wndView.DisplayOff=false;	
		}
	}
	
}

bool CMainFrame::MakeReport(CString misname,CString dpath)
{
bool olddisp=GameWnd->m_wndView.DisplayOff;
	GameWnd->m_wndView.DisplayOff=true;	
	ObjMan->ClearModifyFlags();
	CloseMission();
	ObjMan->ClearModifyFlags();
	FileStream file;
	file.Open(dpath+"\\"+misname+".report",FileStream::WriteOnly);
	if(LoadMission(misname,false))
	{
		CMissionReport rpt;
		CString rpttext;
		rpt.GetReport(rpttext);
		rpttext.Replace("\n","\x0D\x0A");
		file<<(LPCSTR)rpttext;
	}
	else
	{
		file<<(LPCSTR)"UnLoadable";
	}
	
	file.Close();
	GameWnd->m_wndView.DisplayOff=olddisp;	
	return true;
}

void CMainFrame::OnUpdateFileSave(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(ObjMan && ObjMan->IsLoaded());
}

void CMainFrame::OnUpdateFileSaveas(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(ObjMan && ObjMan->IsLoaded());
}

void CMainFrame::OnUpdateOptionsMissionreport(CCmdUI* pCmdUI) 
{
	pCmdUI->Enable(ObjMan && ObjMan->IsLoaded());
}

void CMainFrame::OnOptionsCameraSettings() 
{
	// TODO: Add your command handler code here
	CCameraSettings dlg(this);
	dlg.m_RevMouse=ObjMan->GetCameraController()->RevMouse;
	dlg.m_Speed=ObjMan->GetCameraController()->GetSpeed();
	dlg.m_FollowTerain=ObjMan->GetCameraController()->TerrainFollow;
	if(dlg.DoModal()==IDOK)
	{
	ObjMan->GetCameraController()->RevMouse=dlg.m_RevMouse?true:false;
	ObjMan->GetCameraController()->TerrainFollow=dlg.m_FollowTerain?true:false;
	ObjMan->GetCameraController()->SetSpeed(dlg.m_Speed);
	}
	
}

void CMainFrame::OnOptionsMissionprops() 
{
	ObjMan->SetProperties(ObjMan,this);	
	Refresher::Instance->WorldRefresh();

}

void CMainFrame::OnToolsCheckscripts()
{
	ObjMan->CheckScripts();

	CString title;
	title.LoadString(ID_COMPLETED);
	
	CString text;
	text.LoadString(ID_SCRIPT_CHECKING_COMPLETE);
	
	MessageBox(text,title,MB_OK + MB_ICONINFORMATION);
}

void CMainFrame::OnOptionsObjectives() 
{
	ObjMan->EditObjectives(this);

}
