#!/Users/boydb1/anaconda/bin/python
# -*- coding: utf-8 -*-
'''
Created on Jan 24, 2013
Edited on February 26,2015

@author: yvernabc
'''

import os
import sys
import getpass
from dax import XnatUtils
from datetime import datetime
    
########################################################################################################
########################################## INSTALL FUNCTIONS ###########################################
########################################################################################################
#add to .xnat_setup    
def add_to_workstation(line,comments):
    #.xnat_profile path
    profile_path=os.environ['HOME']+'/.xnat_profile'
    if comments[1]!='#':
        comments='#'+comments
    #If no xnat_profile, create it and add to bash_profile the call for it
    if not os.path.exists(profile_path):
        init_profile(profile_path)
    #add the line and comments:
    if not line in open(profile_path).read():
        with open(profile_path,"a") as bashrc:
            bashrc.write(comments+'\n')
            bashrc.write(line+'\n')  

def init_profile(profile_path):
    comments= '###### XNAT CONFIGURATION FILE ######\n#File running every time you open a new terminal (called by .bash_profile) : created by XnatCheckLogin on '+str(datetime.now())+'\n'
    #Create the file:
    with open(profile_path,"w") as bashrc:
        bashrc.write(comments+'\n')
    
    #link the file in the bashrc or profile
    bash_profile_path=os.environ['HOME']+'/.bash_profile'
    #Add the line in bash_profile
    if os.path.exists(bash_profile_path):
        if not 'source ~/.xnat_profile' in open(bash_profile_path).read():
            with open(bash_profile_path, "a") as bash_profile:
                bash_profile.write("#call for .xnat_profile files containing xnat logins: \n")
                bash_profile.write("source ~/.xnat_profile\n")
                
def check_env(variableName,encrypted=False):
    if variableName in os.environ:
        if encrypted: print ' * '+variableName+' found in your environment variables.'
        else: print ' * '+variableName+' found in your environment variables: '+os.environ[variableName]
        return os.environ[variableName]
    else:
        print ' * '+variableName+' not found.'
        if encrypted:
            return getpass.getpass(prompt='  --> Enter '+variableName+':')
        else:
            if variableName=='XNAT_HOST':
                value=raw_input('  --> Enter '+variableName+' (enter "default" for Vanderbilt XNAT):')
                if value=="default":
                    return 'http://xnat.vanderbilt.edu:8080/xnat'
                else:
                    return value
            else:
                return raw_input('  --> Enter '+variableName+':')
        
def set_xnat_variables():
    print 'INFO: Checking XNAT variables:'
    # XNAT_HOST URL
    XNAT_HOST=check_env('XNAT_HOST')
    # XNAT_USER username
    XNAT_USER=check_env('XNAT_USER')
    # XNAT_PASS password
    XNAT_PASS=check_env('XNAT_PASS',encrypted=True)   
    print "INFO: Trying to open a connection with XNAT with your login..."
    #Check that the the user can open a connection to XNAT and close it
    #connection
    from pyxnat import Interface
    xnat=Interface(XNAT_HOST,XNAT_USER,XNAT_PASS)
    try:
        #check connection
        list_projects = XnatUtils.list_projects(xnat)
        xnat.disconnect()
        print ' -->Good login.'
    except:
        print ' --> error: Wrong login.'
        print ' *Try typing them again:'
        XNAT_HOST = raw_input("  --> XNAT_HOST: ")
        XNAT_USER = raw_input("  --> XNAT_USER: ")
        XNAT_PASS = getpass.getpass(prompt='  --> XNAT_PASS:')
        xnat=Interface(XNAT_HOST,XNAT_USER,XNAT_PASS)
        try:
            #check connection
            list_projects = XnatUtils.list_projects(xnat)
            xnat.disconnect()
            print '  -->Good login.'
        except:
            print '  --> error: Wrong login.'
            solution="""To check if you have the good login, follow these steps: 
    1) Check on XNAT that you are typing the good information (Username/Password)
    2) Check on your system the value that are set with this command:
       echo $XNAT_USER 
       echo $XNAT_PASS
       if the values are wrong, edit your configuration file (either: .xnat_profile or .profile or .bashrc)
    3) close your terminal, open it again and run XnatCheckLogin one more time.
=================================================================================
            """
            print solution
            sys.exit() 
                   
    #Send to the .xnat_profile
    if not 'XNAT_HOST' in os.environ or not 'XNAT_USER' in os.environ or not 'XNAT_PASS' in os.environ:
        print "INFO: Setting your XNAT variables to .xnat_profile"
        add_to_workstation('export XNAT_HOST='+XNAT_HOST,"#Xnat host address")
        print " *XNAT_HOST set up in ~/.xnat_profile"
        add_to_workstation('export XNAT_USER='+XNAT_USER,"#Xnat username")
        print " *XNAT_USER set up in ~/.xnat_profile"
        add_to_workstation('export XNAT_PASS='+XNAT_PASS,"#Xnat password")
        print " *XNAT_PASS set up in ~/.xnat_profile"
        
        print "WARNING: Please run the configuration file .xnat_profile:  'source ~/.xnat_profile'  to apply the changes or open a new terminal."
                
def parse_args():
    from argparse import ArgumentParser
    ap = ArgumentParser(prog='Xnatsetup', description="Set and Check the logins for XNAT.")
    return ap.parse_args()
         
if __name__ == '__main__':
    args = parse_args()
    print '================================================================================='
    set_xnat_variables()
    print '================================================================================='
    
