/* -*- Mode: C++; indent-tabs-mode: nil; c-basic-offset: 8 c-style: "K&R" -*- */

/* Gnome gxsm - Gnome X Scanning Microscopy
 * universal STM/AFM/SARLS/SPALEED/... controlling and
 * data analysis software
 *
 * Gxsm Plugin Name: g_dat_im_export.C
 * ========================================
 * 
 * Copyright (C) 1999 The Free Software Foundation
 *
 * Authors: Percy Zahl <zahl@fkp.uni-hannover.de>
 * additional features: Andreas Klust <klust@fkp.uni-hannover.de>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * 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.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
 */

/* Please do not change the Begin/End lines of this comment section!
 * this is a LaTeX style section used for auto generation of the PlugIn Manual 
 * Chapter. Add a complete PlugIn documentation inbetween the Begin/End marks!
 * --------------------------------------------------------------------------------
% BeginPlugInDocuSection
% PlugInDocuCaption: SPA--LEED (SPA4) d2d data file Import
% PlugInName: spa4_im_export
% PlugInAuthor: Percy Zahl
% PlugInAuthorEmail: zahl@users.sf.net
% PlugInMenuPath: File/Import/SPA4-d2d

% PlugInDescription
\label{plugins:spa4_d2d_im_export}
The \GxsmEmph{spa4\_d2d\_im\_export} plug-in supports reading of SPA--LEED (SPA4) d2d data files.

PlugIn in construction.

% PlugInUsage
The plug-in is called by \GxsmMenu{File/Import/SPA4-d2d}.

% OptPlugInKnownBugs
Not yet tested.

% EndPlugInDocuSection
 * -------------------------------------------------------------------------------- 
 */

#include <gtk/gtk.h>
#include "config.h"
#include "plugin.h"
#include "dataio.h"
#include "action_id.h"
#include "util.h"
#include "batch.h"
#include "fileio.c"
#include "glbvars.h"
#include "surface.h"


using namespace std;

// Plugin Prototypes
static void spa4_im_export_init (void);
static void spa4_im_export_query (void);
static void spa4_im_export_about (void);
static void spa4_im_export_configure (void);
static void spa4_im_export_cleanup (void);

static void spa4_im_export_filecheck_load_callback (gpointer data );
static void spa4_im_export_filecheck_save_callback (gpointer data );

static void spa4_im_export_import_callback (GSimpleAction *simple, GVariant *parameter, gpointer user_data);
static void spa4_im_export_export_callback (GSimpleAction *simple, GVariant *parameter, gpointer user_data);

// Fill in the GxsmPlugin Description here
GxsmPlugin spa4_im_export_pi = {
  NULL,                   // filled in and used by Gxsm, don't touch !
  NULL,                   // filled in and used by Gxsm, don't touch !
  0,                      // filled in and used by Gxsm, don't touch !
  NULL,                   // The Gxsm-App Class Ref.pointer (called "gapp" in Gxsm) is 
                          // filled in here by Gxsm on Plugin load, 
                          // just after init() is called !!!
  "Spa4_Im_Export",
  NULL,                   // PlugIn's Categorie, set to NULL for all, I just don't want this always to be loaded!
  // Description, is shown by PluginViewer (Plugin: listplugin, Tools->Plugin Details)
  NULL,
  "Percy Zahl",
  "file-import-section,file-export-section",
  N_("SPA4-d2d,SPA4-d2d"),
  N_("SPA4 d2d import,SPA4 d2d export"),
  N_("SPA-LEED (SPA4) d2d data file import and export filter."),
  NULL,          // error msg, plugin may put error status msg here later
  NULL,          // Plugin Status, managed by Gxsm, plugin may manipulate it too
  spa4_im_export_init,
  spa4_im_export_query,
  // about-function, can be "NULL"
  // can be called by "Plugin Details"
  spa4_im_export_about,
  // configure-function, can be "NULL"
  // can be called by "Plugin Details"
  spa4_im_export_configure,
  // run-function, can be "NULL", if non-Zero and no query defined, 
  // it is called on menupath->"plugin"
  NULL,
  // cleanup-function, can be "NULL"
  // called if present at plugin removal
  spa4_im_export_import_callback, // direct menu entry callback1 or NULL
  spa4_im_export_export_callback, // direct menu entry callback2 or NULL

  spa4_im_export_cleanup
};

// Text used in Aboutbox, please update!!
  static const char *about_text = N_("GXSM SPA4 'd2d' data file Import/Export Plugin\n\n");

static const char *file_mask = "*.d2d";

// Symbol "get_gxsm_plugin_info" is resolved by dlsym from Gxsm, used to get Plugin's info!! 
// Essential Plugin Function!!
GxsmPlugin *get_gxsm_plugin_info ( void ){ 
  spa4_im_export_pi.description = g_strdup_printf(N_("Gxsm im_export plugin %s"), VERSION);
  return &spa4_im_export_pi; 
}

// Query Function, installs Plugin's in File/Import and Export Menupaths!
// ----------------------------------------------------------------------
// Import Menupath is "File/Import/GME Dat"
// Export Menupath is "File/Export/GME Dat"
// ----------------------------------------------------------------------
// !!!! make sure the "spa4_im_export_cleanup()" function (see below) !!!!
// !!!! removes the correct menuentries !!!!

static void spa4_im_export_query(void)
{
	if(spa4_im_export_pi.status) g_free(spa4_im_export_pi.status); 
	spa4_im_export_pi.status = g_strconcat (
		N_("Plugin query has attached "),
		spa4_im_export_pi.name, 
		N_(": File IO Filters are ready to use."),
		NULL);


// register this plugins filecheck functions with Gxsm now!
// This allows Gxsm to check files from DnD, open, 
// and cmdline sources against all known formats automatically - no explicit im/export is necessary.
	spa4_im_export_pi.app->ConnectPluginToLoadFileEvent (spa4_im_export_filecheck_load_callback);
	spa4_im_export_pi.app->ConnectPluginToSaveFileEvent (spa4_im_export_filecheck_save_callback);
}


// 5.) Start here with the plugins code, vars def., etc.... here.
// ----------------------------------------------------------------------
//


// init-Function
static void spa4_im_export_init(void)
{
	PI_DEBUG (DBG_L2, spa4_im_export_pi.name << "Plugin Init");
}

// about-Function
static void spa4_im_export_about(void)
{
	const gchar *authors[] = { spa4_im_export_pi.authors, NULL};
	gtk_show_about_dialog (NULL, 
			       "program-name",  spa4_im_export_pi.name,
			       "version", VERSION,
			       "license", GTK_LICENSE_GPL_3_0,
			       "comments", about_text,
			       "authors", authors,
			       NULL
			       );
}

// configure-Function
static void spa4_im_export_configure(void)
{
	if(spa4_im_export_pi.app)
		spa4_im_export_pi.app->message("spa4_im_export Plugin Configuration");
}

// cleanup-Function, make sure the Menustrings are matching those above!!!
static void spa4_im_export_cleanup(void)
{
#if 0
	gchar **path  = g_strsplit (spa4_im_export_pi.menupath, ",", 2);
	gchar **entry = g_strsplit (spa4_im_export_pi.menuentry, ",", 2);

	gchar *tmp = g_strconcat (path[0], entry[0], NULL);
	gnome_app_remove_menus (GNOME_APP (spa4_im_export_pi.app->getApp()), tmp, 1);
	g_free (tmp);

	tmp = g_strconcat (path[1], entry[1], NULL);
	gnome_app_remove_menus (GNOME_APP (spa4_im_export_pi.app->getApp()), tmp, 1);
	g_free (tmp);

	g_strfreev (path);
	g_strfreev (entry);
#endif
	PI_DEBUG (DBG_L2, "Plugin Cleanup done.");
}

// make a new derivate of the base class "Dataio"
class spa4_ImExportFile : public Dataio{
public:
	spa4_ImExportFile(Scan *s, const char *n) : Dataio(s,n){ };
	virtual FIO_STATUS Read(xsm::open_mode mode=xsm::open_mode::replace);
	virtual FIO_STATUS Write();
private:
	FIO_STATUS import(const char *fname);
};

FIO_STATUS spa4_ImExportFile::Read(xsm::open_mode mode){
	FIO_STATUS ret;
	gchar *fname=NULL;

	fname = (gchar*)name;

	// name should have at least 4 chars: ".ext"
	if (fname == NULL || strlen(fname) < 4)
		return  FIO_NOT_RESPONSIBLE_FOR_THAT_FILE;
 
	// check for file exists and is OK !
	// else open File Dlg
	ifstream f;
	f.open(fname, ios::in);
	if(!f.good()){
		PI_DEBUG (DBG_L2, "Error at file open. File not good/readable.");
		return status=FIO_OPEN_ERR;
	}
	f.close();

	// Check all known File Types:
	if ((ret=import (fname)) !=  FIO_NOT_RESPONSIBLE_FOR_THAT_FILE)
		return ret;

	return  FIO_NOT_RESPONSIBLE_FOR_THAT_FILE;
}

FIO_STATUS spa4_ImExportFile::import(const char *fname){
	D2D_SPA_DAT_HEADER d2d;
	char fill[48];
	union RAW { guint64 i; gdouble f; } raw;

	// Am I resposible for that file, is it a "Gme-Dat" format ?
	ifstream f;
	GString *FileList=NULL;

	if (strncasecmp(fname+strlen(fname)-4,".d2d",4)){
		f.close ();
		return status=FIO_NOT_RESPONSIBLE_FOR_THAT_FILE;
	}

	f.open(name, ios::in);
	if (!f.good())
	        return status=FIO_OPEN_ERR;
	

	f.read ((char*)&d2d, sizeof (d2d));
	f.read ((char*)&fill, sizeof (fill));
	
	if (WORDS_BIGENDIAN){
		d2d.PointsX = GINT16_FROM_LE (d2d.PointsX);
		d2d.PointsY = GINT16_FROM_LE (d2d.PointsY);

		raw.f = d2d.XYdist;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.XYdist = raw.f;

		raw.f = d2d.Xo;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.Xo = raw.f;

		raw.f = d2d.Yo;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.Yo = raw.f;

		raw.f = d2d.GateTime;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.GateTime = raw.f;

		raw.f = d2d.Energy;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.Energy = raw.f;

		raw.f = d2d.CpsLow;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.CpsLow = raw.f;

		raw.f = d2d.CpsHigh;
		raw.i = GUINT64_FROM_LE (raw.i);
		d2d.CpsHigh = raw.f;
	}

	time_t t; // Scan - Startzeit eintragen 
	time(&t);
	gchar *tmp = g_strconcat ((ctime(&t)), " (Imported)", NULL); scan->data.ui.SetDateOfScan (tmp); g_free (tmp);
	scan->data.ui.SetName (fname);
	scan->data.ui.SetOriginalName (fname);
	scan->data.ui.SetType ("old dat"); 


	// this is mandatory.
	scan->data.s.ntimes  = 1;
	scan->data.s.nvalues = 1;
  
  
	// put some usefull values in the ui structure
	if(getlogin()){
		scan->data.ui.SetUser (getlogin());
	}
	else{
		scan->data.ui.SetUser ("unkonwn user");
	}

	// initialize scan structure -- this is a minimum example
	scan->data.s.nx = d2d.PointsX;
	scan->data.s.ny = d2d.PointsY;
	scan->data.s.dx = d2d.XYdist/d2d.PointsX;;
	scan->data.s.dy = d2d.XYdist*d2d.PointsY/d2d.PointsX/d2d.PointsX;
	scan->data.s.dz = 1;
	scan->data.s.rx = scan->data.s.nx*scan->data.s.dx;
	scan->data.s.ry = scan->data.s.ny*scan->data.s.dy;
	scan->data.s.x0 = d2d.Xo;
	scan->data.s.y0 = d2d.Yo;
	scan->data.s.alpha = 0;

	// be nice and reset this to some defined state
	scan->data.s.GateTime = d2d.GateTime*1e-3;
	scan->data.s.Energy   = d2d.Energy;
	scan->data.s.SPA_OrgX     = 0.;
	scan->data.s.SPA_OrgY     = 0.;
	scan->data.display.z_high       = d2d.CpsHigh;
	scan->data.display.z_low        = d2d.CpsLow;

	// set the default view parameters
	scan->data.display.bright = 32.;
	scan->data.display.contrast = 1.0;

	// FYI: (PZ)
	//  scan->data.display.vrange_z  = ; // View Range Z in base ZUnits
	//  scan->data.display.voffset_z = 0; // View Offset Z in base ZUnits
	//  scan->AutoDisplay([...]); // may be used too...
  

	FileList = g_string_new ("Imported by GXSM from SPA4-d2d data file.\n");
	g_string_append_printf (FileList, "Original Filename: %s\n", fname);
	g_string_append (FileList, "Orig. Comment: ");
	g_string_append (FileList, d2d.comment);
	g_string_append (FileList, "\n");
	g_string_append (FileList, "Orig. Date of Scan: ");
	g_string_append (FileList, d2d.dateofscan);
	g_string_append (FileList, "\n");

	scan->data.ui.SetComment (FileList->str);
	g_string_free(FileList, TRUE); 
	FileList=NULL;

	scan->data.s.dx = scan->data.s.rx / scan->data.s.nx;
	scan->data.s.dy = scan->data.s.ry / scan->data.s.ny;

	// Read Img Data.
	scan->mem2d->Resize (scan->data.s.nx, scan->data.s.ny);
	scan->mem2d->DataD2DRead (f, d2d.GateTime);

	scan->data.orgmode = SCAN_ORG_CENTER;
	scan->mem2d->data->MkXLookup (-scan->data.s.rx/2., scan->data.s.rx/2.);
	scan->mem2d->data->MkYLookup (scan->data.s.ry/2., -scan->data.s.ry/2.);
  
	scan->mem2d->add_layer_information (new LayerInformation ("Energy", d2d.Energy, "%5.1f eV"));
	scan->mem2d->add_layer_information (new LayerInformation ("Length", d2d.XYdist, "%5.1f V"));
	scan->mem2d->add_layer_information (new LayerInformation ("Gate", d2d.GateTime, "%5.1f ms"));
	scan->mem2d->add_layer_information (new LayerInformation ("PointsX", d2d.PointsX, "%5.0f"));
	scan->mem2d->add_layer_information (new LayerInformation ("PointsY", d2d.PointsY, "%5.0f"));

	return FIO_OK; 
}


FIO_STATUS spa4_ImExportFile::Write(){
	gchar tmp[0x4004];
	const gchar *fname;
	ofstream f;

	memset (tmp, 0, sizeof (tmp));

	if(strlen(name)>0)
		fname = (const char*)name;
	else
		fname = main_get_gapp()->file_dialog("File Export: SPA4 d2d"," ",file_mask,"","SPA4 d2d write");
	if (fname == NULL) return FIO_NO_NAME;

	// check if we like to handle this
	if (strncmp(fname+strlen(fname)-4,".d2d",4))
		return FIO_NOT_RESPONSIBLE_FOR_THAT_FILE;


        GtkWidget *dialog = gtk_message_dialog_new (NULL,
						    GTK_DIALOG_DESTROY_WITH_PARENT,
						    GTK_MESSAGE_INFO,
						    GTK_BUTTONS_OK,
						    N_("Sorry, not yet implemented.")
						    );
        gtk_widget_show (dialog);

        int response = GTK_RESPONSE_NONE;
        g_signal_connect (G_OBJECT (dialog), "response", G_CALLBACK (GnomeAppService::on_dialog_response_to_user_data), &response);
        
        // FIX-ME GTK4 ??
        // wait here on response
        while (response == GTK_RESPONSE_NONE)
                while(g_main_context_pending (NULL)) g_main_context_iteration (NULL, FALSE);

        return FIO_NOT_RESPONSIBLE_FOR_THAT_FILE;

#if 0

        f.open(name, ios::out);
	if (!f.good())
	        return status=FIO_OPEN_ERR;

//	scan->mem2d->DataWrite(f);
#endif
  return FIO_OK; 
}

// Plugin's Notify Cb's, registered to be called on file load/save to check file
// return via filepointer, it is set to Zero or passed as Zero if file has been processed!
// That's all fine, you should just change the Text Stings below...


static void spa4_im_export_filecheck_load_callback (gpointer data ){
	gchar **fn = (gchar**)data;
	if (*fn){
		PI_DEBUG (DBG_L2, 
			  "Check File: spa4_im_export_filecheck_load_callback called with >"
			  << *fn << "<" );

		Scan *dst = main_get_gapp()->xsm->GetActiveScan();
		if(!dst){ 
			main_get_gapp()->xsm->ActivateFreeChannel();
			dst = main_get_gapp()->xsm->GetActiveScan();
		}
		spa4_ImExportFile fileobj (dst, *fn);

		FIO_STATUS ret = fileobj.Read(); 
		if (ret != FIO_OK){ 
			// I'am responsible! (But failed)
			if (ret != FIO_NOT_RESPONSIBLE_FOR_THAT_FILE)
				*fn=NULL;
			// no more data: remove allocated and unused scan now, force!
//			main_get_gapp()->xsm->SetMode(-1, ID_CH_M_OFF, TRUE); 
			PI_DEBUG (DBG_L2, "Read Error " << ((int)ret) << "!!!!!!!!" );
		}else{
			// got it!
			*fn=NULL;

			// Now update gxsm main window data fields
			main_get_gapp()->xsm->ActiveScan->GetDataSet(main_get_gapp()->xsm->data);
			main_get_gapp()->spm_update_all();
			dst->draw();
		}
	}else{
		PI_DEBUG (DBG_L2, "spa4_im_export_filecheck_load: Skipping" );
	}
}

static void spa4_im_export_filecheck_save_callback (gpointer data ){
	gchar **fn = (gchar**)data;
	if (*fn){
		Scan *src;
		PI_DEBUG (DBG_L2,
			  "Check File: spa4_im_export_filecheck_save_callback called with >"
			  << *fn << "<" );

		spa4_ImExportFile fileobj (src = main_get_gapp()->xsm->GetActiveScan(), *fn);

		FIO_STATUS ret;
		ret = fileobj.Write(); 

		if(ret != FIO_OK){
			// I'am responsible! (But failed)
			if (ret != FIO_NOT_RESPONSIBLE_FOR_THAT_FILE)
				*fn=NULL;
			PI_DEBUG (DBG_L2, "Write Error " << ((int)ret) << "!!!!!!!!" );
		}else{
			// write done!
			*fn=NULL;
		}
	}else{
		PI_DEBUG (DBG_L2, "spa4_im_export_filecheck_save: Skipping >" << *fn << "<" );
	}
}

// Menu Call Back Fkte

static void spa4_im_export_import_callback (GSimpleAction *simple, GVariant *parameter, gpointer user_data){
	gchar **help = g_strsplit (spa4_im_export_pi.help, ",", 2);
	gchar *dlgid = g_strconcat (spa4_im_export_pi.name, "-import", NULL);
	gchar *fn = main_get_gapp()->file_dialog_load (help[0], NULL, file_mask, NULL);
	g_strfreev (help); 
	g_free (dlgid);
	if (fn){
	        spa4_im_export_filecheck_load_callback (&fn );
                g_free (fn);
	}
}

static void spa4_im_export_export_callback (GSimpleAction *simple, GVariant *parameter, gpointer user_data){
	gchar **help = g_strsplit (spa4_im_export_pi.help, ",", 2);
	gchar *dlgid = g_strconcat (spa4_im_export_pi.name, "-export", NULL);
	gchar *fn = main_get_gapp()->file_dialog_save (help[0], NULL, file_mask, NULL);
	g_strfreev (help); 
	g_free (dlgid);
	if (fn){
	        spa4_im_export_filecheck_save_callback (&fn );
                g_free (fn);
	}
}
