/***************************** LICENSE START ***********************************

 Copyright 2012 ECMWF and INPE. This software is distributed under the terms
 of the Apache License version 2.0. In applying this license, ECMWF does not
 waive the privileges and immunities granted to it by virtue of its status as
 an Intergovernmental Organization or submit itself to any jurisdiction.

 ***************************** LICENSE END *************************************/

#include <Xm/Xm.h>
#include <Tab.h>
#include <Drag.h>

#ifndef Confirm_H
#include "Confirm.h"
#endif

#ifndef Help_H
#include "Help.h"
#endif

#ifndef Resources_H
#include "Resources.h"
#endif

#ifndef FolderWindow_H
#include "FolderWindow.h"
#endif

#ifndef Folder_H
#include "Folder.h"
#endif

#ifndef IconInfo_H
#include "IconInfo.h"
#endif

#ifndef Request_H
#include "Request.h"
#endif

#ifndef Runnable_H
#include "Runnable.h"
#endif

#ifndef IconClass_H
#include "IconClass.h"
#endif

#ifndef MetviewUI_H
#include "MetviewUI.h"
#endif

#ifndef Dropping_H
#include "Dropping.h"
#endif

#ifndef Tools_H
#include "Tools.h"
#endif

#ifndef Items_H
#include "Items.h"
#endif


typedef map<FolderH,FolderWindow*> Map;
static Map folders;

FolderWindow::FolderWindow(Folder* icon):
	FolderViewer(icon),
	Timeout(10)
{

	folder_->notifyOpened();
	string name = folder_->fullName();

	Widget top = MetviewUI::root();

	create(XtDisplay(top),"Metview",0,0);

	folders[folder_] = this;

	loadResources();
	XtSetSensitive(top_,folder_ != Folder::top());
	XtSetSensitive(up_, folder_ != Folder::top());

	//-- title bar, for main window use env.variable value --
	const char* cstr=name.empty()?getenv("METVIEW_VERSION_TITLE"):name.c_str();
	if( cstr )
	  {
	    XtVaSetValues(xd_rootwidget(),XmNtitle,cstr,0);
	    XtVaSetValues(xd_rootwidget(),XmNiconName,cstr,0);
	  }
	XtRealizeWidget(xd_rootwidget());

	drawers_.install(drawer_);
	TabClose(drawer_);
	enable();

	FolderViewer::install(drag_);
	Tools::make(tools_);
	recents_.install(recent_);
	recents_.top(folder_);

	((IconObject*)folder_)->addObserver((IconObserver*)this);

}

FolderWindow::~FolderWindow()
{
	saveResources();
	XtDestroyWidget(xd_rootwidget());
	folders.erase(folder_);
	folder_->notifyClosed();
	((IconObject*)folder_)->removeObserver((IconObserver*)this);
}

void FolderWindow::open(Folder* icon)
{
	Map::iterator j = folders.find(icon);
	if(j != folders.end())
		(*j).second->raise();
	else
		new FolderWindow(icon);
}

void FolderWindow::close(Folder* icon)
{
	Map::iterator j = folders.find(icon);
	if(j != folders.end())
		(*j).second->close();
}

void FolderWindow::start()
{
	vector<string> opened;
	Resources::get("OPEN",opened);
	int n = 0;
	for(vector<string>::iterator j = opened.begin(); j != opened.end(); ++j)
	{
		Folder *f = Folder::folder(*j,false);
		if(f) 
		{ 	
			open(f);
			n++;
		}
	}

	if(n == 0) open(Folder::top());
}


void FolderWindow::raise()
{
	XMapRaised(XtDisplay(xd_rootwidget()),XtWindow(xd_rootwidget()));
}

void FolderWindow::close()
{
	closeCB(NULL, NULL);
}

void FolderWindow::closeCB(Widget,XtPointer)
{
	if(folders.size() == 1)
		stop();
	else
		delete this;
}

void FolderWindow::exitCB(Widget,XtPointer)
{
	if(Confirm::ask(true,"Quit Metview?"))
		stop();
}

void FolderWindow::stop()
{
	vector<string> opened;

	while(folders.size())
	{
		Map::iterator j = folders.begin();
		FolderWindow* f = (*j).second;
		opened.push_back(f->folder_->fullName());
		delete f;
	}

	Resources::set("OPEN",opened);
	Resources::sync();
	exit(0);
}

void FolderWindow::sortByNameCB(Widget,XtPointer)
{
	 sortByName();
}

void FolderWindow::sortByClassCB(Widget,XtPointer)
{
	 sortByClass();
}

void FolderWindow::run()
{
	folder_->scan();
}

void FolderWindow::commandCB(Widget,XtPointer data)
{
	XmRowColumnCallbackStruct *cb = (XmRowColumnCallbackStruct *) data;
	string a(XtName(cb->widget));

	for(vector<IconObjectH>::iterator j = current_.begin() ; 
		j != current_.end(); ++j)
			(*j)->command(a);
}


void FolderWindow::doubleClick(IconObject* o)
{
	o->doubleClick();
}

bool FolderWindow::clone()
{
	return false;
}

Path FolderWindow::prefFile()
{
	return folder_->dotPath();
}

void FolderWindow::loadResources()
{
	Request r(prefFile());

	Dimension w,h;
	Boolean small ;

	w     = (long)r("WIDTH");
	h     = (long)r("HEIGHT");

	const char *s = r("SMALL_ICONS");
	small = s != 0 && strcmp(s,"TRUE") == 0;

	if(w == 0) w = 500;
	if(h == 0) h = 300;

	XtVaSetValues(form_,
		XmNwidth, w,
		XmNheight,h,
		0);

	XtVaSetValues(drag_,
		XmNsmallIcons, small,
		NULL);
}

void FolderWindow::saveResources()
{
	Request r(prefFile());
	Dimension w,h;

	XtVaGetValues(form_,
		XmNwidth, &w,
		XmNheight,&h,
		0);

	r("WIDTH")  = (long)w;
	r("HEIGHT") = (long)h;

	Boolean small ;
	XtVaGetValues(drag_,
		XmNsmallIcons, &small,
		NULL);

	r("SMALL_ICONS") = small ? "TRUE" : "FALSE";

	r.save(prefFile());
	
}


Widget FolderWindow::menu()
{
	if(current_.size() == 0)
		return menu_;

	set<string> c;

	for(vector<IconObjectH>::iterator j = current_.begin() ; j != current_.end(); ++j)
	{
		if(c.size() == 0)
			c = (*j)->can();
		else {
			set<string> d = (*j)->can();
			set<string> e;

			set_intersection(
				c.begin(),c.end(),
				d.begin(),d.end(),
				inserter(e,e.begin()));

			c = e;
		}
	}


	WidgetList w;
	int count;

	XtVaGetValues(commands_,
		XmNchildren,&w,
		XmNnumChildren,&count,
		0);
			
	for(int i = 2; i < count; i++)
	{
		const char* p = XtName(w[i]);
		XtSetSensitive(w[i],c.find(p) != c.end());
	}

	return commands_;
}


void FolderWindow::fileMapCB(Widget, XtPointer)
{
	XtSetSensitive(close_,folders.size()>1);
}

void FolderWindow::toggleSizeCB(Widget, XtPointer)
{
	toggleSize();
}

void FolderWindow::rescanCB(Widget, XtPointer)
{
	folder_->scan();
}

void FolderWindow::where(IconObject* o,int& x,int& y)
{
	IconInfo& info = o->info();
	x = info.x();
	y = info.y();
	if(x == 0 && y == 0)
		XtVaSetValues(drag_,XmNautoPlace,True,0);
	else
		XtVaSetValues(drag_,XmNautoPlace,False,0);
}

#if 0

void FolderWindow::arrived(IconObject* o)
{
	if(!o->visible()) return;

	if(DragFindIconByData(widget_,o) == 0)
	{
		const char* n = o->name().c_str();
		const char* c = o->className().c_str();
		IconInfo& info = o->info();
		Position x = info.x();
		Position y = info.y();

		if(*n == '.') return;


		Icon i = DragAddIcon(widget_, c, n, o, info.x(), info.y());

		if(x == 0 && y == 0)
		{
			XtVaSetValues(widget_,XmNautoPlace,False,0);
			DragFindPositionIcon(widget_,i,&x,&y);
			o->position(x,y);
		}

		// We should find the state here...

	}
}

#endif

void FolderWindow::recentCB(Widget,XtPointer data)
{
	XmRowColumnCallbackStruct *cb = (XmRowColumnCallbackStruct *) data;
	const char* n = XtName(cb->widget);

	if( strcmp(n,"..") == 0 )        //-- if 'parent folder' then build
	  {
	    string fn = folder_->fullName();
	    n = mdirname( fn.c_str() );
	  }

	recents_.open(n);
}

void FolderWindow::showLastCB(Widget,XtPointer)
{
	DragShowLast(widget_);
}

void FolderWindow::newIconCB(Widget,XtPointer)
{
	newIcon();
}

void FolderWindow::newLinkCB(Widget,XtPointer)
{
	newLink();
}

void FolderWindow::prefCB(Widget,XtPointer)
{
	IconObject* o = Items::find("general");
	if(o) o->edit();
}

void FolderWindow::changed(IconObject* o)
{
	if(o == folder_)
	{
		string name = folder_->fullName();	
		XtVaSetValues(xd_rootwidget(),XmNtitle,name.c_str(),0);
		XtVaSetValues(xd_rootwidget(),XmNiconName,name.c_str(),0);
	}
}

void FolderWindow::destroyed(IconObject* o)
{
	if(o == folder_)
		delete this;
}
	// From DropSite

void FolderWindow::drop(Dropping& d)
{
	FolderViewer::drop(d);
}

void FolderWindow::move(IconObject* o,int x,int y,IconObject *on)
{
	o->position(x,y);
	if(on) on->drop(o);
}

void FolderWindow::copy(IconObject* o,int x,int y,IconObject *on)
{
	Folder *f = dynamic_cast<Folder*>(on);
	if(!f) f = o->parent();

//	int oldx = 0;
//	int oldy = 0;

//	iconPosition(o,oldx,oldy);

	IconObject *c = o->clone(f);

	f->position(c,x,y);
//	f->position(o,oldx,oldy);
}

void FolderWindow::messagesCB(Widget,XtPointer)
{
	Folder::top()->showLog();
}

void FolderWindow::helpMenuCB(Widget,XtPointer data)
{
	XmRowColumnCallbackStruct *cb =(XmRowColumnCallbackStruct *) data;
	Help::show(XtName(cb->widget));
}
