/*

    Bist: a chemical drawing tool
    Copyright (C) 2008 Valerio Benfante

    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 3 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, see <http://www.gnu.org/licenses/>.
*/
#include <FL/x.H>
#include <X11/xpm.h>
#include <icon.xpm>
#include <config.h>
#include <config_path.h>
#include <global.hpp>


#include <wordexp.h>
#include <sys/stat.h>
#include <dirent.h>
#include <cerrno>
//portability problem?
#include <pthread.h>

#include <cstdio>


#include <cairo/cairo.h>
#include <pango/pangocairo.h>


#include <FL/Fl.H>
#include <FL/Fl_Image.H>
#include <FL/Fl_Pixmap.H>
#include <FL/Fl_Double_Window.H>
#include <FL/Fl_Scroll.H>
#include <FL/fl_ask.H>
#include <FL/Fl_Menu_Bar.H>
#include <FL/Fl_Menu_Item.H>
#include <FL/Fl_Toggle_Button.H>
#include <FL/Fl_Menu_Button.H>
#include <FL/Fl_Choice.H>
#include <FL/Fl_Light_Button.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Help_Dialog.H>
//#include <FL/Fl_PNG_Image.H>

#include <interfacce.hpp>
#include <legame.hpp>
#include <etichetta.hpp>
#include <multiline_label.hpp>
#include <multifont_label.hpp>
#include <paragraph_text.hpp>
#include <atomo.hpp>
#include <procedura.hpp>
#include <gruppo.hpp>
#include <immagine.hpp>
#include <bist_plugin.hpp>
#include <mol_canvas.hpp>
#include <finestra_pr.hpp>
#include <editor.hpp>

#include <prefs.hpp>

#include <set_conf.hpp>
#include <command_line.hpp>
#include <util.hpp>

#include <font_factory.hpp>

finestra_pr* MainWindow;

Preferences  __pref;



Fl_Menu_Item* voci_menu;



#define CMDLINEOPT "vhc:f:"


static struct option long_options[] ={

  {"help",no_argument,NULL,'h'},
  {"version",no_argument,NULL,'v'},
  {"covert-to",required_argument,NULL,'c'},
  {"input-file",required_argument,NULL,'f'},
  {0,0,0,0}
};






int main(int argc , char** argv){
  setup_conf();
  setlocale (LC_ALL, "");
  textdomain (TEXT_DOMAIN); 
  bindtextdomain (TEXT_DOMAIN, CATALOG_DIR);

  string format_output;
  int option_v;
  int indice_arg;
  bool convert=false;
  string file_input="";


  while((option_v=getopt_long (argc, argv, CMDLINEOPT, 
			       long_options,&indice_arg))!=-1){

    switch(option_v){
    case 'h':
      print_help(argv[0]);
      exit(EXIT_SUCCESS);
      break;
    case 'v':
      print_version();
      exit(EXIT_SUCCESS);
      break;
      
   case 'f':
      {
	file_input=optarg;
	if(file_input[0]=='-'){
	  cerr << ELF << "\t" << _("Option requires an argument -- f") << endl;
	  exit(EXIT_FAILURE);
	}else{
	  convert=true;
	}
	break;
      }

    case 'c':
      {
	string oparg=optarg;
	if(oparg[0]=='-'){
	  cerr << ELF << "\t" << _("Option requires an argument -- c") << endl;
	  exit(EXIT_FAILURE);
	}else{
	  if(format_supported(oparg)){
	    format_output=optarg;

	  }else{
	    cerr << ELF << "\t" << _("format") << " " 
		 << oparg << " " 
		 << _("not supported, switching to ps") << endl;
	    format_output="ps";

	  }
	}
	break;
      }
    case '?':
      print_version();
      print_help(argv[0]);
      exit(EXIT_FAILURE);
      break;
    }
  }




  if(convert){
    wordexp_t res;
    int funz=wordexp (file_input.c_str(), &res, WRDE_SHOWERR | WRDE_UNDEF);
    if(!funz){
      for(unsigned int i=0;i<res.we_wordc;i++){
	string filenamein=res.we_wordv[i];
	string filenameout="";
	string::size_type posd=filenamein.rfind(".");
	if(posd!=string::npos){
	  filenameout=filenamein.substr(0,posd)+ "."  + format_output;
	}else{
	  filenameout=filenamein + "."  + format_output;
	}
	convert_to_vector_format(string(res.we_wordv[i]),
				 string(filenameout),format_output.c_str());
      }
      wordfree(&res); 
      exit(EXIT_SUCCESS);
    }else{
      std::cerr << _("Error in path:") <<  " " << file_input << std::endl;
      exit(EXIT_FAILURE);
    }
  }else{
  
    Fl_Menu_Item vc_menu[28] = {
      {_("&File")       , FL_ALT+'f'          , 0                     , 0, FL_SUBMENU},
      {_("&New")        , FL_CTRL+'n'         , copy_cb               , 0},
      {_("&Open")       , FL_CTRL+'o'         , open_file_cb          , 0},
      {_("&Save")       , FL_CTRL+'s'         , editor_save_native    , 0},
      {_("Save &as...") , FL_CTRL+FL_SHIFT+'s', save_as_native_file_cb, 0},
      {_("&Export")     , FL_CTRL+'e'         , editor_export         ,0},
      {_(PREFS_RECENT_FILES_LABEL), 0         , 0                     ,0, FL_SUBMENU},
      {0},
      {_("&Quit")       , FL_CTRL+'q'         , quit_cb               ,0,0},
      {0}, 
      {_("Edit"),        FL_ALT+'e', 0, 0, FL_SUBMENU},
      {_("Paste"),      FL_CTRL+'v', editor_paste_cb, 0},
      {_("Undo"),      FL_CTRL+'z', editor_undo_cb, 0},
      {_("Redo"),      FL_CTRL+FL_SHIFT+'z', editor_redo_cb, 0},
      {_("Erase"),     FL_Delete, delete_selected_cb,0},
      {0},
      {_("&Configuration"), 0, 0, 0, FL_SUBMENU},
      {_("Set values"),     0, config_cb, 0},
      {_("Reset to default"), 0, editor_set_def_cb, 0},
      {0},
      {_("&Plug-in"),        0, 0, 0, FL_SUBMENU},
      {0},
      {_("&Help"),         FL_F+1, 0, 0, FL_SUBMENU},
      {_("About..."),      0, edit_about_cb, 0},
      {_("No Warranty"),   0,edit_nowar_cb,0},
      {_("Turorial"),0,edit_tutorial_cb,0},
      {0},
      {0}
    };

    ::voci_menu=vc_menu;
  
    fl_open_display();                // needed as display has not been previously opened
    //Fl::scheme("plastic"); 

    
    //set_actual_font_from_prefs();

    Fl::visual(FL_DOUBLE|FL_INDEX);
    editor window(FIN_W,FIN_H,ELF);
    Splash_Window  splash;

    MainWindow=&window;
    if(argc>1){
      if(string(argv[1])=="redfog"){
	print_redfog_wisdom();
	exit(EXIT_SUCCESS);
      }else{
	window.file_inp(argv[1]);
      }
    }


            
    Pixmap p, mask;
    
    XpmCreatePixmapFromData(fl_display, DefaultRootWindow(fl_display),
			    const_cast<char**>(icon_xpm), &p, &mask, NULL);

    window.icon((char *)p);
    
    window.show();

    if(__pref.getSplash()){
      splash.show();
    }

   
    Fl::run();

    font_map_singleton::free_context();
    exit(EXIT_SUCCESS);
  }
}

