# -*- coding: utf-8 -*-
#
# ccwatcher (http://ccwatcher.sourceforge.net/)
# Copyright (C) 2009-2013 Xaver Wurzenberger <xaverxn at users.sourceforge.net>
#
# This program is free software; you can redistribute and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2, 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.

from ccw_messages import dict_hardcodedsettings
import ccw_settingshandler
import os, sys

textoutput = ''
silent = False

def mprint(mystring):
    global textoutput, silent
    if silent==True:
        textoutput += "\n"
        textoutput += mystring
    else:
        print mystring



def whereis(program): #inspired by: http://jimmyg.org/blog/2009/working-with-python-subprocess.html
    for path in os.environ.get('PATH', '').split(':'):
        if os.path.exists(os.path.join(path, program)) and not os.path.isdir(os.path.join(path, program)):
            return os.path.join(path, program) # => returns the FIRST hit
    return None



def main(bool_silent = False, onlyread = False,  avo = '', gnu = '',  plot = ''):

    global silent
    silent = bool_silent
    
    textoutput, avo, gnuplotpath, plotsystem = gather_info(avo, gnu, plot)

    if onlyread == False:
        mprint("DONE - Trying to write ini-File...")
        print write_ini(avo, gnuplotpath, plotsystem)
        
        mprint("FINISHED\n")

    return textoutput, avo, gnuplotpath, plotsystem


def gather_info(avo = '', gnu = '',  plot = ''):
    global textoutput, silent
    textoutput = ''
    settingsfile = ccw_settingshandler.getSettingsFileLocation()
    inisettings = ccw_settingshandler.readSettings(settingsfile) #this seems to deliver hardcodedsettings if there is no settingsfile found

    
    mprint("CHECK1 - Python version:")
    if sys.version_info[0] == 2 and 4 <= sys.version_info[1] <= 7:
        mprint("\tOK - Your python version is '"+sys.version[0:5]+"'. This should be fine.")
    elif sys.version_info[0] == 2:
        mprint("\tYour python version ("+sys.version[0:5]+") is untested. ccwatcher may or may not work.")
    else:
        mprint("\tWARNING - Your python version is different to 2. ccwatcher probably won't work.")
    
    mprint("CHECK2 - O/S:")
    if "linux" in sys.platform: #there is no os.uname() in win32
        mprint("\tOK - Linux is fine.")
    else:
        mprint("\tccwatcher was written for GNU/Linux; you seem to be using another operating system.")
        mprint("\tIt should basically work, but some features may not - ASCII plotting can't work on Win32 systems for instance. See readme for further details.")
    
    mprint("CHECK3 - PyQt4:")
    try:
        from PyQt4 import QtGui
    except ImportError:
        mprint("\tWARNING - PyQt does not seem to be present. You can use ccwatcher only in the command-line mode.")
    else:
        mprint("\tOK")
    
    
    mprint("CHECK4 - Avogadro:")
    if avo == '':
        if whereis('avogadro'):
            avo == whereis('avogadro')
        elif len(inisettings['str_avogadro_path']):
            avo = inisettings['str_avogadro_path']
    
    if os.path.exists(avo):
        mprint("\tOK - Avogadro is in your PATH")
    else:
        mprint("\tCouldn't find program 'Avogadro'.\n\tIf you wish to use it make sure it's in your PATH.")
    mprint("\tYou can change the path to Avogadro from the GUI or in the .ini file.")
    

    mprint("CHECK5 - Gnuplot:") #results from ini file are neglected it seems!?
    if os.path.exists(gnu):
        gnuplotpath = gnu
    else:
        if os.path.exists(os.path.join('gnuplot400', 'bin','pgnuplot.exe')):
            gnuplotpath = os.path.join('gnuplot400', 'bin','pgnuplot.exe')
        elif sys.platform.startswith('win') and whereis('pgnuplot.exe'): #In Windows: _p_gnuplot
            gnuplotpath = whereis('pgnuplot.exe')
        elif whereis('gnuplot'):
            gnuplotpath = whereis('gnuplot')
        elif len(inisettings['str_gnuplot_path']):
            gnuplotpath = inisettings['str_gnuplot_path']
        else:
            gnuplotpath = ''
    
    if gnuplotpath:
        mprint("\tOK - Gnuplot seems to be: "+gnuplotpath)
    else:
        mprint("\tGnutplot could not be found. To use it, enter the executable path below.")
        if sys.platform.startswith('win'):
            gnuplotpath = os.path.join('gnuplot400', 'bin', 'pgnuplot.exe')
        else:
            gnuplotpath = os.path.join('gnuplot', 'bin', 'gnuplot')
            
    if silent == False:
        gnuplotpath2 = raw_input("Enter Gnuplot path (default is ["+gnuplotpath+"]):")
        if gnuplotpath2:
            gnuplotpath = os.path.abspath(gnuplotpath2)

    mprint("CHECK6 - Qwt:")
    plotsystem = inisettings['str_plot_system'] #if there's no ini file, this is set to 'qwt' as per hardcodedsettings
    try:
        from PyQt4 import Qwt5
    except:
        mprint("\tWARNING - Qwt5 not found! Falling back to Gnuplot...")
        plotsystem = 'gnuplot'
    else:
        mprint("\tOK")

    if silent == False and plotsystem == 'qwt':
        plotsystem2 = raw_input("Default GUI plot system is Qwt. Type 'gnu' if you prefer Gnuplot:")
        if plotsystem2 in ("gnu","'gnu'","gnuplot","Gnuplot"):
            mprint('\tGnuplot selected')
            plotsystem = 'gnuplot'
        else:
            plotsystem = 'qwt'


    return textoutput, avo, gnuplotpath, plotsystem



def write_ini(avo, gnuplotpath, plotsystem):
    import shutil
    messages = ""
    
    if avo:
        dict_hardcodedsettings['str_avogadro_path'] = avo
        
    dict_hardcodedsettings['str_gnuplot_path'] = gnuplotpath
    dict_hardcodedsettings['str_plot_system'] = plotsystem
        
    settingsfile = ccw_settingshandler.getSettingsFileLocation()
    if os.getenv("XDG_CONFIG_HOME") and os.getenv("XDG_CONFIG_HOME") in settingsfile: #This should work even for problematic cases and Non-Linux OS's.
        if os.path.exists(os.path.join(os.getenv("HOME"),".config","ccwatcher","ccwatcher.ini")) and settingsfile not in os.path.join(os.getenv("HOME"),".config","ccwatcher","ccwatcher.ini"): #Exception should only happen here if HOME is not existant - not likely if XDG_CONFIG_HOME exists
            oldsettingsfile = os.path.join(os.getenv("HOME"),".config","ccwatcher","ccwatcher.ini") #XDG_CONFIG_HOME might be different from .config in rare cases
            shutil.move(oldsettingsfile, settingsfile+'.bak')
            shutil.rmtree(os.path.join(os.getenv("HOME"),".config","ccwatcher"))
            messages += "Your old settings file "+oldsettingsfile+"has been backed up as "+settingsfile+".bak2 and the parent directory was removed.\n"
        if os.path.exists(os.path.join(os.getenv("HOME"),".ccwatcher","ccwatcher.ini")): #no elif because several old ones may exist
            oldsettingsfile = os.path.join(os.getenv("HOME"),".ccwatcher","ccwatcher.ini")
            shutil.move(oldsettingsfile, settingsfile+'.bak2') 
            shutil.rmtree(os.path.join(os.getenv("HOME"),".ccwatcher"))
            messages += "Your old settings file "+oldsettingsfile+" has been backed up as "+settingsfile+".bak1 and the parent directory was removed.\n"
            
    #if os.path.exists(settingsfile):
    messages += "Writing a new config file to "+settingsfile+".\n"
    messages += "Your old one is backed up as: "+settingsfile+".bak.\n"
    shutil.move(settingsfile, settingsfile+'.bak') 
    ccw_settingshandler.writeSettings(dict_hardcodedsettings.copy(), settingsfile) #this is silent as we have the info lines right above

    return messages




if __name__ == '__main__': 
    main()
