/**********************************************************************
 
	Copyright (C) 2003-2004
	Hirohisa MORI <joshua@nichibun.ac.jp>
	Tomoki SEKIYAMA <sekiyama@yahoo.co.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/



#include "v/VWindow.h"
#include "VApplication.h"

#include "v/VLayout.h"

extern "C" {
#include	"utils.h"
#include	"pri_level.h"
}

#include <LUndoer.h>
#include <LWindowHeader.h>
#include <LPushButton.h>

void AddDefaultButton(LPane *pane, LPushButton *button);
void RemoveDefaultButton(LPane *pane, LPushButton *button);
void AddCancelButton(LPane *pane, LPushButton *button);
void RemoveCancelButton(LPane *pane, LPushButton *button);

extern VCustomizedMenuBar *	menu_no_window;

const SInt16	length_Big		= 16000;

class CWindow : public LWindow
{
public:
	CWindow(
			ResIDT				inWINDid,
			UInt32				inAttributes,
			LCommander*			inSuperCommander,
			int					category,
			VCustomizedMenuBar*	menu,
			VWindow*			vwin)
		: LWindow(inWINDid, inAttributes, inSuperCommander), 
		  mCategory(category), mMenuBar(menu), mVWindow(vwin),
		  mDefaultButtons(0), mCancelButtons(0)
		{
		}
	
	virtual void	ResizeFrameBy(
				SInt16		inWidthDelta,
				SInt16		inHeightDelta,
				Boolean		inRefresh)
		{
			LWindow::ResizeFrameBy(inWidthDelta, inHeightDelta, inRefresh);
			if (mUserCon && (inWidthDelta !=0 || inHeightDelta != 0) ) {
				VLayout::mark(mVWindow);
			}
		}

	virtual void		AttemptClose()
		{
			if ((mSuperCommander == nil) || mSuperCommander->AllowSubRemoval(this)) {
				if ( mVWindow->attempt_close() ) {
					SendSelfAE(kAECoreSuite, kAEClose, ExecuteAE_No);
					Hide();
					vq_insert_callback(mVWindow,v_object_destroyer,0,0,0);
				}
			}
		}

	virtual void		DoClose()
		{
			if ((mSuperCommander == nil) || mSuperCommander->AllowSubRemoval(this)) {
				if ( mVWindow->attempt_close() ) {
					SendSelfAE(kAECoreSuite, kAEClose, ExecuteAE_No);
					Hide();
					vq_insert_callback(mVWindow,v_object_destroyer,0,0,0);
				}
			}
		}
	virtual void		ActivateSelf() 
		{ VCustomizedMenuBarImp::switch_to_menu(mMenuBar); LWindow::ActivateSelf(); }
	virtual void		DeactivateSelf()
		{ VCustomizedMenuBarImp::switch_to_menu(menu_no_window); LWindow::DeactivateSelf(); }
	
	virtual void		FindCommandStatus(
								CommandT			inCommand,
								Boolean&			outEnabled,
								Boolean&			outUsesMark,
								UInt16&				outMark,
								Str255				outName)
		{
			short flag;
			if ( mMenuBar && inCommand < 0 && mMenuBar->get_menu_flag(inCommand, &flag) ) {
				outEnabled = flag & VMF_ENABLED;
				outUsesMark = flag & VMF_CHECKED;
				if ( outUsesMark )
					outMark = checkMark;
			}
			else {
				LWindow::FindCommandStatus(inCommand, outEnabled,
										outUsesMark, outMark, outName);
			}
		}
	virtual Boolean			ObeyCommand(
								CommandT			inCommand,
								void*				ioParam = nil)
		{
			if ( mMenuBar && inCommand < 0 && mMenuBar->menu_choosed(inCommand) )
				return true;
			return LWindow::ObeyCommand(inCommand, ioParam);
		}

	virtual Boolean		HandleKeyPress( const EventRecord& inKeyEvent )
		{
			ButtonList *list;
			if ( inKeyEvent.modifiers == 0 &&
					( (inKeyEvent.message & charCodeMask ) == char_Return ||
					  (inKeyEvent.message & charCodeMask ) == char_Enter ) ) {
				for ( list = mDefaultButtons ; list ; list = list->next ) {
					if ( list->btn->IsActive() ) {
						list->btn->BroadcastMessage(msg_ValueChanged, 0);
						return TRUE;
					}
				}
			}
			else if ( UKeyFilters::IsEscapeKey(inKeyEvent) ||
						UKeyFilters::IsCmdPeriod(inKeyEvent) ) {
				for ( list = mCancelButtons ; list ; list = list->next ) {
					if ( list->btn->IsActive() ) {
						list->btn->BroadcastMessage(msg_ValueChanged, 0);
						return TRUE;
					}
				}
			}
			return FALSE;
		}
	void				AddDefaultButton( LPushButton*	button )
		{
			AddToButtonList(button, &mDefaultButtons);
		}
	void				RemoveDefaultButton( LPushButton*	button )
		{
			RemoveFromButtonList(button, &mDefaultButtons);
		}
	void				AddCancelButton( LPushButton*	button )
		{
			AddToButtonList(button, &mCancelButtons);
		}
	void				RemoveCancelButton( LPushButton*	button )
		{
			RemoveFromButtonList(button, &mCancelButtons);
		}


  protected:
	VCustomizedMenuBar*	mMenuBar;
	int					mCategory;
	VWindow *			mVWindow;
	struct ButtonList {
		LPushButton *	btn;
		ButtonList *	next;
	} *mDefaultButtons, *mCancelButtons;

	void				AddToButtonList( LPushButton*	button, ButtonList **list )
		{
			ButtonList *newList = new ButtonList;
			newList->btn = button;
			newList->next = *list;
			*list = newList;
		}
	void				RemoveFromButtonList( LPushButton*	button, ButtonList **list )
		{
			ButtonList *prev = 0, *target;
			for ( target = *list ; target ; prev = target, target = target->next ) {
				if ( target->btn == button ) {
					if ( prev )
						prev->next = target->next;
					else
						*list = target->next;
					delete target;
					return;
				}
			}
		}
};

void
AddDefaultButton(LPane *pane, LPushButton *button)
{
	((CWindow*)pane)->AddDefaultButton(button);
}
void
RemoveDefaultButton(LPane *pane, LPushButton *button)
{
	((CWindow*)pane)->RemoveDefaultButton(button);
}
void
AddCancelButton(LPane *pane, LPushButton *button)
{
	((CWindow*)pane)->AddCancelButton(button);
}
void
RemoveCancelButton(LPane *pane, LPushButton *button)
{
	((CWindow*)pane)->RemoveCancelButton(button);
}


VExError
VWindow::create_do(const VObjectStatus *s, int flags,VObject * nmp, void * arg)
{
	window_close_handler = 0;
	sts.min_size = (VSize){V_WINDOW_MIN_WIDTH, V_WINDOW_MIN_HEIGHT};

	category = *(int*)arg;
	menu_bar = VCustomizedMenuBar::create(category, this);
	
	if ( flags & VSF_ATTR )
		sts.attr = s->attr;
	else
		sts.attr = 0;
	
	UInt32 attributes;
	attributes = (sts.attr & floating) ? (windAttr_Floating | windAttr_HideOnSuspend) :
				( sts.attr & modal ) ? 	windAttr_Modal : windAttr_Regular;
	attributes |= windAttr_TitleBar | windAttr_Enabled | windAttr_Targetable;
	if ( ! (sts.attr & modal) )
		attributes |= windAttr_CloseBox;
	if ( sts.attr & resizable )
		attributes |= windAttr_Resizable | windAttr_SizeBox | windAttr_Zoomable;
	CWindow* win = new CWindow((sts.attr & floating) ? WIND_V_FLOATING_RES : WIND_V_DEFAULT_RES,
			attributes, theApp, category, menu_bar, this);
	win->AddAttachment(new LUndoer);
	win->SetMinMaxSize((Rect){V_WINDOW_MIN_WIDTH,V_WINDOW_MIN_HEIGHT,length_Big,length_Big});
	win->SetStandardSize((SDimension16){V_WINDOW_MIN_WIDTH,V_WINDOW_MIN_HEIGHT});
	win->ResizeWindowTo(V_WINDOW_MIN_WIDTH,V_WINDOW_MIN_HEIGHT);
	win->SetUserCon((long)this);

	SDimension16 size;
	win->GetFrameSize(size);

	SPaneInfo paneInfo = { sts.id, size.width, size.height, true, true, 
			(SBooleanRect){true,true,true,true}, 0, 0, (long)this, win };
	SViewInfo viewInfo = { (SDimension32){size.width, size.height}, {0,0}, {1,1}, false };
	LWindowHeader *pla = new LWindowHeader(paneInfo, viewInfo);
	pla->FinishCreate();
	info = pla;
	
	win->FinishCreate();

	{
		VLayout layout;	// calc min size
		layout.layout_in_frame(this, true);
	}
	return nmp->add_child_do(this);
}

void
VWindow::destroy_do(VObject * nmp)
{
	nmp->remove_child_do(this);
	if ( info ) { // info can be set NULL on close
//		((LWindowHeader*)info)->GetSuperView()->Hide();
		VLayout::unmark(this);
		delete ((LWindowHeader*)info)->GetSuperView();
	}
	if ( menu_bar ) {
		delete menu_bar;
	}
}

VWindow::~VWindow()
{
}

VExError
VWindow::get_status(VObjectStatus *s, int flags) const
{
	V_OP_START_EX
	VExError err = initial_VExError(V_ER_NO_ERR,flags,0);
	CWindow *win = (CWindow*)((LWindowHeader *)info)->GetSuperView();
	if ( flags & VSF_ATTR ) {
		s->attr = sts.attr;
		if ( win->HasAttribute(windAttr_Resizable) )
			s->attr |= resizable;
		else
			s->attr &= ~resizable;
		if ( win->HasAttribute(windAttr_Modal) )
			s->attr |= modal;
		else
			s->attr &= ~modal;
		if ( win->HasAttribute(windAttr_Floating) )
			s->attr |= floating;
		else
			s->attr &= ~floating;
		flags &= ~VSF_ATTR;
	}
	if ( flags & VSF_ENABLED ) {
		s->enabled = win->IsEnabled();
		flags &= ~VSF_ENABLED;
	}
	Rect rect;
	if ( flags & (VSF_POSITION | VSF_SIZE) ) {
		win->GetGlobalBounds(rect);
	}
	if ( flags & VSF_SIZE ) {
		s->size.w = rect.right - rect.left;
		s->size.h = rect.bottom - rect.top;
		flags &= ~VSF_SIZE;
	}
	if ( flags & VSF_POSITION ) {
		s->position.x = rect.left;
		s->position.y = rect.top;
		flags &= ~VSF_POSITION;
	}
	err.subcode1 = flags;
	VExError err2 = VObject::get_status(s,flags);
	if ( err2.code )
		err = merge_VExError_vstatus_type(err,err2);
	
	V_OP_END
	return err;
}

VExError
VWindow::set_status(const VObjectStatus *s, int flags)
{
	V_OP_START_EX
	VExError err = initial_VExError(V_ER_NO_ERR,flags,0);
	CWindow *win = (CWindow*)((LWindowHeader *)info)->GetSuperView();
	if ( flags & VSF_ATTR ) {
		if ( s->attr & resizable )
			win->SetAttribute(windAttr_Resizable | windAttr_SizeBox | windAttr_Zoomable);
		else
			win->ClearAttribute(windAttr_Resizable | windAttr_SizeBox | windAttr_Zoomable);
		if ( s->attr & modal )
			win->SetAttribute(windAttr_Modal);
		else
			win->ClearAttribute(windAttr_Modal);
		if ( s->attr & floating )
			win->SetAttribute(windAttr_Floating);
		else
			win->ClearAttribute(windAttr_Floating);
		if ( ! (s->attr & modal) && ! (s->attr & floating) )
			win->SetAttribute(windAttr_Regular);
		else
			win->ClearAttribute(windAttr_Regular);
		err.subcode1 &= ~VSF_ATTR;
	}
	if ( flags & VSF_DESC ) {
		if ( s->descriptor ) {
			LStr255 str(n_string(std_cm, const_cast<L_CHAR*>(s->descriptor)));
			win->SetDescriptor(str);
		}
		else
			win->SetDescriptor("\p");
		err.subcode1 &= ~VSF_DESC;
	}
	if ( flags & VSF_VERTD ) {
		err.subcode1 &= ~VSF_VERTD;
	}
	if ( flags & VSF_ENABLED ) {
		if ( s->enabled )
			win->Enable();
		else
			win->Disable();
		err.subcode1 &= ~VSF_ENABLED;
	}
	if ( flags & VSF_MIN_SIZE ) {
		short w = V_WINDOW_MIN_WIDTH, h = V_WINDOW_MIN_HEIGHT;
		if ( s->min_size.w != V_DEFAULT_SIZE )
			w = s->min_size.w;
		if ( s->min_size.h != V_DEFAULT_SIZE )
			h = s->min_size.h;
		if ( w < V_WINDOW_MIN_WIDTH )
			w = V_WINDOW_MIN_WIDTH;
		if ( h < V_WINDOW_MIN_HEIGHT )
			h = V_WINDOW_MIN_HEIGHT;
		win->SetMinMaxSize((Rect){h, w, length_Big, length_Big});
		win->SetStandardSize((SDimension16){w, h});
		err.subcode1 &= ~VSF_MIN_SIZE;
	}
	if ( flags & VSF_SIZE ) {
		SDimension16 frame, new_frame;
		win->GetFrameSize(frame);
		if ( s->size.w == V_DEFAULT_SIZE && s->size.h == V_DEFAULT_SIZE ) {
			new_frame.width = sts.min_size.w;
			new_frame.height = sts.min_size.h;
		}
		else {
			new_frame.width = s->size.w;
			new_frame.height = s->size.h;
		}
		if ( frame.width != new_frame.width || frame.height != new_frame.height )
			win->ResizeWindowTo(new_frame.width, new_frame.height);
		err.subcode1 &= ~VSF_SIZE;
	}
	if ( flags & VSF_POSITION ) {
		win->MoveWindowTo(s->position.x, s->position.y);
		err.subcode1 &= ~VSF_POSITION;
	}

	VExError err2 = VObject::set_status(s,flags);
	if ( err2.code )
		err = merge_VExError_vstatus_type(err,err2);

	if ( flags & VSF_CALC_MIN ) {
		if ( sts.children )
			sts.children->object->set_status(0, VSF_CALC_MIN);
		VLayout layout;
		layout.layout_in_frame(this, true);
		sts.min_size = layout.parent_min_size();
		if ( ! (sts.attr & resizable) )
			win->ResizeWindowTo(sts.min_size.w, sts.min_size.h);
		err.subcode1 &= ~VSF_CALC_MIN;
	}
	if ( flags & VSF_LAYOUT ) {
		VLayout layout;
		layout.layout_in_frame(this);
		layout.do_layout(this);
		err.subcode1 &= ~VSF_LAYOUT;
	}

	if ( flags & VSF_VISIBLE ) {
		if ( s->visible ) {
			sts.visible = true;
			VLayout::mark(this);
			VLayout::layout_marked_window();
			win->Show();
		}
		else
			win->Hide();
		err.subcode1 &= ~VSF_VISIBLE;
	}
	V_OP_END

	if ( flags & ( VSF_PADDING | VSF_ALIGN ) ) {
		VLayout::mark(this);
		err.subcode1 &= ~( VSF_PADDING | VSF_ALIGN );
	}
	return err;
}

bool
VWindow::attempt_close()
{
	if ( window_close_handler == 0 ) {
		return true;
	}	
	vq_insert_callback(this,window_close_handler,user_arg,0,0);
	return false;
}


void
VWindow::redraw(VRect* rect) const
{
	if ( ! info )
		return;
	_V_OP_START()
	if ( rect )
		info->RefreshRect((Rect){rect->t, rect->l, rect->b, rect->r});
	else
		info->Refresh();
	V_OP_END
}


VExError
VWindow::add_child_do(VObject* child)
{
	VLayout layout;	// calc min size
	layout.layout_in_frame(this, true);
	return initial_VExError(V_ER_NO_ERR,0,0);
}

void
VWindow::remove_child_do(VObject* child)
{
	// do nothing
}

void
VWindow::child_status_changed(VObject* child, VInfo* info)
{
	// do nothing - object is marked when status is changed
}

