'''Utility functions used to add new authorized E-log users or change their authorization.'''

import os
import sys
import cx_Oracle

MCC_LOGBOOK_ID = 122
SPEAR3_LOGBOOK_ID = 187
SSRL_BLDO_LOGBOOK_ID = 189

#
# The get_account_name function returns a selected
# UNIX account name from information displayed from
# an input file containing user name/account name 
# information.  The input account name file contains
# information generated  from invoking the UNIX
# "ypcat passwd" command, filtered by the supplied
# user last name.
#
def get_account_name(account_names_file):

#
#   Read each line from the input account names file.
#   Split each line into fields separated by the
#   colon delimiter and then append a tuple containing
#   the user name (field 4) and account name (field 0)
#   fields to a list. 
#
    name_account = []
    with open(account_names_file) as file:
        for line in file:
            line = line.rstrip()

            fields = line.split(":")

            name_account.append((fields[4], fields[0]))

#
#   Sort the list containing tuples with user name/
#   account name elements by the user name.
#
    sorted_name_account = sorted(name_account, key=lambda tup: tup[1])
    num_accounts = len(sorted_name_account)

#
#   Print each entry of the sorted list containing
#   user name/account name elements with an integer
#   preceding it (the first element's associated
#   integer is 1).  The person adding a new authorized
#   E-log user is prompted to select the line's
#   integer associated with the user name/account name
#   for the user to be added as an authorized user (or
#   0 if no user name/account name line is appropriate).
#   If an invalid response is given, repeat the prompt
#   requesting a line be selected until a valid response
#   is entered.
#
    valid_input = False
    while not valid_input:
        print "Choose a number below corresponding to the desired UNIX account for the supplied last name or enter 0 to exit if no account is appropriate:"
        i = 1
    
        for account in sorted_name_account:
            print i, " ", account[0], " ", account[1]
            i = i + 1

        print " "
        selected_number_str = raw_input('Enter a number: ')

        try:
            selected_number_int = int(selected_number_str)
            if ((selected_number_int >= 0) and (selected_number_int <= num_accounts)):
                valid_input = True
            else:
                print "Selected number not in valid range-- try again."
                print " "
        except ValueError:
            print "Value entered is not an integer-- try again."
            print " "
            valid_input = False

#
#   If 0 was entered, a null account name is returned.
#
    if (selected_number_int == 0):
        account_name = ""
    else:
        account_name =  sorted_name_account[selected_number_int - 1][1]

    return account_name

#
# The insert_into_oracle function inserts a row into the Operations
# E-log Oracle table elog_users and multiple rows into the logbook_users
# table if there is no row in the elog_users table that already contains
# the supplied UNIX account name (referred to as "username" in this
# function).  If there is a row that already contains the supplied
# UNIX account name, the user to be added as an authorized E-log user
# was previously added and this function returns an error status (1).
#
def insert_into_oracle(username, firstname, lastname, authorization_type):
    status = 0

#
#   Connect to the Oracle instance MCCO, the Oracle instance containing
#   Operations E-log system information.  Then check whether there is
#   already a row in the elog_users table with the same username as the
#   supplied username.  If there is, exit with an error status (1).
#
    
    cnx = cx_Oracle.connect("/@MCCO")
    try:
        select_cursor = cnx.cursor()
        select_cursor.execute("SELECT LASTNAME FROM ELOG_USERS WHERE USERNAME = '" + username + "'")
        num_rows = len(select_cursor.fetchall())
        select_cursor.close()
        if (num_rows != 0):
            print "Username ", username, " is already in the list of authorized users-- exiting."
            status = 1
            return status
        else:
#
#           Set the next user id (the user id of the user to be added as an
#           new authorized elog user) to one more than the current largest
#           user id.
#
            select_cursor = cnx.cursor()
            select_cursor.execute("SELECT MAX(USER_ID) FROM ELOG_USERS")
            for (max_user_id) in select_cursor:
                next_user_id = max_user_id[0] + 1 

#
#               Insert a new row into the elog_users table for the new
#               authorized elog user.
#
                insert_sql_1 = "INSERT INTO ELOG_USERS (USER_ID, USERNAME, FIRSTNAME, LASTNAME, EMAIL, ADMIN) \
                               VALUES (:user_id, :username, :firstname, :lastname, NULL, NULL)"
                insert_cursor = cnx.cursor()
                insert_cursor.execute(insert_sql_1, user_id=next_user_id, username=username, firstname=firstname, lastname=lastname)
                insert_cursor.close()

#
#               For each row in the logbooks table (one entry per logbook),
#               check whether the new authorized elog user is authorized to
#               make entries into the associated logbook.  If it is,
#               insert a row into the logbook_users table containing the
#               associated logbook id and the new authorized elog user's
#               user id. 
#
                select_cursor_2 = cnx.cursor()
                select_cursor_2.execute("SELECT LOGBOOK_ID FROM LOGBOOKS ORDER BY LOGBOOK_ID")
                for (cur_logbook_row) in select_cursor_2:
                    logbook_id = cur_logbook_row[0]

                    insert_logbook_users_row = False
                    if (logbook_id == MCC_LOGBOOK_ID):
                        if (authorization_type == "MCC"):
                            insert_logbook_users_row = True
                    elif (logbook_id == SPEAR3_LOGBOOK_ID):
                        if (authorization_type == "SPEAR3"):
                            insert_logbook_users_row = True
                    elif (logbook_id == SSRL_BLDO_LOGBOOK_ID):
                        if (authorization_type == "SSRL-BLDO"):
                            insert_logbook_users_row = True
                    else:
                        insert_logbook_users_row = True 
 
                    if insert_logbook_users_row:
                        insert_sql_2 = "INSERT INTO LOGBOOK_USERS (LOGBOOK_ID, USER_ID) \
                                       VALUES (:logbook_id, :user_id)"
                        insert_cursor = cnx.cursor()
                        insert_cursor.execute(insert_sql_2, logbook_id=logbook_id, user_id=next_user_id)
                        insert_cursor.close()

                select_cursor_2.close()
            select_cursor.close()

            cnx.commit()

    except cx_Oracle.DatabaseError as err:
        print("Database error {}".format(err))
        status = 1
        return status

    cnx.close()

    return status


def db_connect():
	conn = None
	try:
		os.environ['TWO_TASK'] = 'MCCO'
		os.environ['TNS_ADMIN'] = '/afs/slac/g/lcls/tools/oracle/wallets/elog_owner'
		conn = cx_Oracle.connect('/@MCCO')
	except cx_Oracle.DatabaseError as e:
		print 'Database error {}'.format(e)
	
	return conn

def db_disconnect(conn):
	try:
		conn.commit()
		conn.close()
	except cx_Oracle.DatabaseError as e:
		print 'Database error {}'.format(e)

# retrieve the current list of restricted logbooks
def get_restricted_logbooks():
	conn = db_connect()
	restricted_list	= []

	try:
		if conn is not None:
			cur = conn.cursor()
			cur.execute('SELECT name FROM logbooks WHERE restricted = \'Y\'')
			restricted_results = cur.fetchall()
			if len(restricted_results) == 0:
				restricted_list.append('No restricted logbooks found')
			else:
				restricted_list = [row[0] for row in restricted_results]	
	except cx_Oracle.DatabaseError as e:
		print 'Database error {}'.format(e)

	if conn is not None:
		db_disconnect(conn)
	
	return restricted_list

# replaces insert_into_oracle()
# for use with add_elog_user.py
def insert_elog_user(username, firstname, lastname, restricted_access):
	status = 0
	os.environ['TWO_TASK'] = 'MCCO'
	os.environ['TNS_ADMIN'] = '/afs/slac/g/lcls/tools/oracle/wallets/elog_owner'
	conn = cx_Oracle.connect('/@MCCO')
	
	try:
		cur = conn.cursor()
		cur.execute('SELECT user_id FROM elog_users WHERE username = \'' + username + '\'')
		num_rows = len(cur.fetchall())

		if num_rows > 0:
			print 'User {} already exists in authorized users list, checking for new logbook access'.format(username)
		else:
			cur.execute('SELECT MAX(user_id) + 1 FROM elog_users')
			next_user_id = cur.fetchone()[0]

			cur.prepare('INSERT INTO elog_users (user_id, username, firstname, lastname, email, admin) \
						VALUES (:user_id, :username, :firstname, :lastname, NULL, NULL)')
			cur.execute(None, {'user_id': next_user_id, 'username': username, 'firstname': firstname, 'lastname': lastname})
			cur.execute('INSERT INTO logbook_users (logbook_id, user_id) \
						SELECT logbook_id,' + `next_user_id` + ' as user_id \
						FROM logbooks WHERE restricted = \'N\'') 

		cur.close()

		# check for restricted access logbook requests
		if len(restricted_access) > 0:
			restricted_cur = conn.cursor()

			restricted_cur.execute('SELECT name, logbook_id FROM logbooks WHERE restricted = \'Y\'')
			restricted_logbooks = restricted_cur.fetchall()
			restricted_dict = {lb_name: lb_id for (lb_name, lb_id) in restricted_logbooks}
			restricted_set = set(lb_name.lower() for lb_name in restricted_dict)
			
			restricted_cur.prepare('SELECT lb.name FROM logbooks lb, logbook_users lbu, elog_users elu \
									WHERE lb.logbook_id = lbu.logbook_id AND lbu.user_id = elu.user_id \
									AND lb.restricted = \'Y\' AND elu.username = :username')
			restricted_cur.execute(None, {'username': username})
			user_restricted_list = restricted_cur.fetchall()
			user_restricted_list = [lb[0].lower() for lb in user_restricted_list]
			user_restricted_set = set(user_restricted_list)

			# use set math to get restricted logbooks the user doesn't have access to	
			restricted_diff = restricted_set.difference(user_restricted_set)

			if len(restricted_logbooks) > 0:
				restricted_cur.execute('SELECT user_id FROM elog_users WHERE username = \'' + username + '\'')
				user_id = restricted_cur.fetchone()[0]
				
				restricted_cur.prepare('INSERT INTO logbook_users (logbook_id, user_id) \
										VALUES (:logbook_id, :user_id)')
					
				for name in restricted_access:
					if name.lower() in restricted_set:
						if name.lower() in restricted_diff:
							restricted_logbook_id = restricted_dict[name]
							restricted_cur.execute(None, {'logbook_id': restricted_logbook_id, 'user_id': user_id})
						else:
							print 'User {} already has access to restricted logbook {}, skipping'.format(username, name)
					else:
						print 'Restricted logbook {} not found in database, skipping'.format(name)
						continue
			else:
				print 'Restricted logbooks {} not found in database, exiting'.format(restricted_access)
				status = 1
				return status

			restricted_cur.close()
	except cx_Oracle.DatabaseError as e:
		print 'Database error {}'.format(e)
		status = 1 

	conn.commit()
	conn.close()

	return status

def insert_elog_logbook(logbook_name, abbreviation, description, restricted):
	status = 0
	conn = db_connect()

	try:
		if conn is not None:
			cur = conn.cursor()
			cur.execute('SELECT logbook_id FROM logbooks WHERE name = \'' + logbook_name + '\'')
			num_rows = len(cur.fetchall())

			if num_rows > 0:
				print 'Logbook {} already exists in the Operations E-Log'.format(logbook_name)
			else:
				cur.execute('SELECT MAX(logbook_id) + 1 FROM logbooks WHERE name != \'TLOG\'')
				next_logbook_id = cur.fetchone()[0]	# fetch returns tuple, so need to dereference first element
				print 'next_logbook_id = {}'.format(next_logbook_id)	
				isRestricted = 'N' 
				if restricted == True:
					isRestricted = 'Y'
					
				cur.prepare('INSERT INTO logbooks(logbook_id, name, abbreviation, description, restricted) \
							VALUES(:logbook_id, :name, :abbreviation, :description, :restricted)')
				cur.execute(None, {'logbook_id': next_logbook_id, 'name': logbook_name, 'abbreviation': abbreviation, 'description': description, 'restricted': isRestricted})
				
				# if unrestricted logbook, grant all current E-Log users access to it
				if restricted == False:
					cur.execute('INSERT INTO logbook_users (logbook_id, user_id) \
								SELECT ' + `next_logbook_id` + ' as logbook_id, user_id \
								FROM elog_users')
					
			cur.close()
								
		else:
			raise cx_Oracle.DatabaseError('Database connection failed')	
	except cx_Oracle.DatabaseError as e:
		print 'Database error {}'.format(e)
		status = 1

	if conn is not None:
		db_disconnect(conn)

	return status


#
# The add_update_elog_authorized_users_files updates pieces of the
# /afs/slac/g/cd/soft/html/elog/users/elog_authorized_users.html
# document for the sections in this document that should contain
# the name ("last name, first name") of the new authorized elog user.
# This is the "all users" section of this document and, if the user
# is authorized to make an entry into a specified restricted logbook,
# the section of this document listing the names of users authorized
# to make entries into this restricted logbook.
#
def add_update_elog_authorized_users_files(firstname, lastname, authorization_type, elog_authorized_users_html_dir):
    status = 0

#
#   If the user is authorized to make entries into the restricted
#   MCC logbook, read the "mcc_users.txt" file from the same directory
#   that contains the  elog_authorized_users.html document.  This
#   file contains the names (in "last name, first name" format)
#   of users authorized to make entries into the MCC logbook.
#   For each line in this file, append the associated "last name,
#   first name" string to the lastname_firstname list.  Then
#   append the "last name, first name" string for the new authorized
#   elog user to this list.  Next, sort this list.  Finally,
#   output a new version of this file containing the sorted
#   list of users authorized to make entries into the logbook
#   including the new authorized elog user.
#
    if (authorization_type == "MCC"):
        mcc_users_file = elog_authorized_users_html_dir + "mcc_users.txt"

        lastname_firstname = []
        with open(mcc_users_file) as file:
            for line in file:
                line = line.rstrip()
                lastname_firstname.append(line)

        lastname_firstname.append(lastname + ", " + firstname)
        sorted_lastname_firstname = sorted(lastname_firstname)

        with open(mcc_users_file, 'w') as file:
            for entry in sorted_lastname_firstname:
                file.write(entry + '\n')

#
#       Write a new version of the "mcc_users_piece.html" file,
#       which contains HTML tags for an ordered list and the
#       same "last name, first name" information in the
#       previously updated version of he mcc_users.txt file.
#
        mcc_users_piece_file = elog_authorized_users_html_dir + "mcc_users_piece.html"
        with open(mcc_users_piece_file, 'w') as file:
            file.write("<ol>\n")
            for entry in sorted_lastname_firstname:
                file.write("<li>" + entry + '</li>\n')
            file.write("</ol>\n")

#
#   If the user is authorized to make entries into the restricted SPEAR3
#   logbook, perform similar processing for this logbook as would be
#   performed if the user was authorized to make entries into the
#   the MCC logbook, as described above.
#
    elif (authorization_type == "SPEAR3"):
        spear3_users_file = elog_authorized_users_html_dir + "spear3_users.txt"

        lastname_firstname = []
        with open(spear3_users_file) as file:
            for line in file:
                line = line.rstrip()
                lastname_firstname.append(line)

        lastname_firstname.append(lastname + ", " + firstname)
        sorted_lastname_firstname = sorted(lastname_firstname)

        with open(spear3_users_file, 'w') as file:
            for entry in sorted_lastname_firstname:
                file.write(entry + '\n')

        spear3_users_piece_file = elog_authorized_users_html_dir + "spear3_users_piece.html"
        with open(spear3_users_piece_file, 'w') as file:
            file.write("<ol>\n")
            for entry in sorted_lastname_firstname:
                file.write("<li>" + entry + '</li>\n')
            file.write("</ol>\n")

#
#   If the user is authorized to make entries into the restricted SSRL-BLDO
#   logbook, perform similar processing for this logbook as would be
#   performed (described above) if the user was authorized to make entries
#   into the MCC logbook, as described above.
#
    elif (authorization_type == "SSRL-BLDO"):
        ssrl_bldo_users_file = elog_authorized_users_html_dir + "ssrl_bldo_users.txt"

        lastname_firstname = []
        with open(ssrl_bldo_users_file) as file:
            for line in file:
                line = line.rstrip()
                lastname_firstname.append(line)

        lastname_firstname.append(lastname + ", " + firstname)
        sorted_lastname_firstname = sorted(lastname_firstname)

        with open(ssrl_bldo_users_file, 'w') as file:
            for entry in sorted_lastname_firstname:
                file.write(entry + '\n')

        ssrl_bldo_users_piece_file = elog_authorized_users_html_dir + "ssrl_bldo_users_piece.html"
        with open(ssrl_bldo_users_piece_file, 'w') as file:
            file.write("<ol>\n")
            for entry in sorted_lastname_firstname:
                file.write("<li>" + entry + '</li>\n')
            file.write("</ol>\n")

#
#   Update the all_users.txt and all_users_piece.html files
#   by adding the name of the new authorzed elog user.
#
    all_users_file = elog_authorized_users_html_dir + "all_users.txt"

    lastname_firstname = []
    with open(all_users_file) as file:
        for line in file:
            line = line.rstrip()
            lastname_firstname.append(line)

    lastname_firstname.append(lastname + ", " + firstname)
    sorted_lastname_firstname = sorted(lastname_firstname)

    with open(all_users_file, 'w') as file:
        for entry in sorted_lastname_firstname:
            file.write(entry + '\n')

    all_users_piece_file = elog_authorized_users_html_dir + "all_users_piece.html"
    with open(all_users_piece_file, 'w') as file:
        file.write("<ol>\n")
        for entry in sorted_lastname_firstname:
            file.write("<li>" + entry + '</li>\n')
        file.write("</ol>\n")

    return status

def remove_from_oracle(username, logbooks):
    status = 0

    conn = cx_Oracle.connect("/@MCCO")
    
    try:
	cur = conn.cursor()
	cur.execute('SELECT user_id FROM elog_users WHERE username = \'' + username + '\'')
	user_id = cur.fetchone()[0] # query result returns a tuple, so need to dereference first element

	if user_id is not None:
	    # get the list of all available logbooks
	    db_logbooks = ()
	    cur.execute('SELECT name from logbooks') 
	    db_logbooks = cur.fetchall()	    
	    
	    # get the list of all logbooks the user has access to
	    user_logbooks = ()
	    cur.execute('SELECT name FROM logbooks lb, logbook_users lbu, elog_users elu WHERE lb.logbook_id = lbu.logbook_id AND lbu.user_id = elu.user_id AND elu.username = \'' + username + '\'')
	    user_logbooks = cur.fetchall()

	    # if the user passes in a list of logbooks, check if each logbook exists in the database, then
	    # remove user access if it has not been done already
	    if len(logbooks) > 0:		
	    	cur.prepare('DELETE FROM logbook_users WHERE user_id = ' + `user_id` + ' AND logbook_id = (SELECT logbook_id FROM logbooks WHERE name = :logbook_name)')
	    	logbook_list = logbooks.split(',')
		for lb in logbook_list:
		    lb_tuple = lb,
		    if lb_tuple in db_logbooks:
			if lb_tuple in user_logbooks:
		            cur.execute(None, {'logbook_name': lb})
			    print 'Removing access to logbook {} for user {}'.format(lb, username)
			else:
			    print 'Logbook {} access already removed for user {}'.format(lb, username)
		    else:
			print 'Logbook {} does not exist, skipping'.format(lb)
	    else: 
		# if no list of specific logbooks is passed in, remove user access from ALL logbooks and 
		# delete user from authorized E-Log Users list
		cur.execute('DELETE FROM logbook_users WHERE user_id = ' + `user_id`)
	    	cur.execute('DELETE FROM elog_users WHERE user_id = ' + `user_id`)

	    conn.commit()
	    cur.close()
	else:
	    raise cx_Oracle.DatabaseError('User {} not found in database'.format(username))

    except cx_Oracle.DatabaseError as e:
        print("Database error {}".format(e))
        status = 1
        return status

    conn.close()

    return status
