/*

    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 <config.h>
#include <config_path.h>
#include <global.hpp>

#include <sys/stat.h>
#include <dirent.h>
#include <cerrno>


#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 <prefs.hpp>

#include <set_conf.hpp>

extern Preferences  __pref;


void setup_conf(){
  struct stat bistconf;
  string home=getenv("HOME");
  string bistdir=home+"/"+CONFIG_DIR+"/";
  int res_stat = stat(bistdir.c_str(),&bistconf);
  if(res_stat==-1 &&  errno==ENOENT){
    int ris=mkdir(bistdir.c_str(),S_IRWXU);
    if(ris<0){
      string err=strerror(errno);
      fl_alert(_("I could not create directory: \"%s\""),(bistdir + ".\n" + err).c_str());
    }


  }


  //check for template directory
  

  std::string templ_path=home + std::string(LIB_PATH_HOME);

  res_stat = stat(bistdir.c_str(),&bistconf);

  if(res_stat==0){ //exist parent directory
    res_stat = stat(templ_path.c_str(),&bistconf);
    if(res_stat==-1 &&  errno==ENOENT){

      int repl_ring=mkdir(templ_path.c_str(),S_IRWXU);
    
      if(repl_ring<0){
        string err=strerror(errno);
        fl_alert(_("I could not create directory: \"%s\""),templ_path.c_str());
      }
    }
  }
  
  string saveconf=home+ "/" +CONFIG_DIR+ "/" +CONFIG_FILE;
  res_stat=stat(saveconf.c_str(),&bistconf);
  __pref.setSaveFile(saveconf.c_str());
  __pref.setFile(saveconf.c_str(), false);

  if(res_stat==-1 && errno==ENOENT){
    __pref.setSaveFile(saveconf.c_str());
    __pref.SavePrefs();
  }else{
    //cout << "ttt" << "carica" << saveconf << endl;
    __pref.LoadPrefs();
  }


}
