#!/usr/bin/env python
'''

@name: add_elog_logbook.py
@author: Patrick Pascual (ppascual@slac.stanford.edu)
@created: 02/09/2016

@description: Script to automate addition of new Operations E-Log logbooks.

'''

import argparse
import elogutils
import os
import re

def main():
	parser = argparse.ArgumentParser(prog='add_elog_logbook', description='Adds an Operations E-Log logbook to the database and sets it as restricted or unrestricted access')
	parser.add_argument('--name', metavar='logbook_name', help='The name of the logbook to be added to the Operations E-Log database')
	parser.add_argument('--abbreviation', required=False, metavar='string', help='Abbreviated name of logbook for display purposes')
	parser.add_argument('--description', metavar='string', nargs='+', help='Description of logbook purpose and users')
	parser.add_argument('--restricted', required=False, action='store_true', help='Whether logbook is restricted or unrestricted access (Default: Unrestricted access)')
	
	args = parser.parse_args()		 

	name_limit = 30
	abbrev_limit = 15
	desc_limit = 80
	blank_desc = '^$'

	if args.name is not None:
		if len(args.name.strip()) == 0:
			parser.error('Logbook name cannot be blank.')
		
		if len(args.name.strip()) > name_limit:
			parser.error('Logbook name cannot exceed {} characters.'.format(name_limit))
		

	if args.abbreviation is not None:
		if len(args.abbreviation.strip()) > abbrev_limit:
			parser.error('Logbook abbreviation cannot exceed {} characters.'.format(abbrev_limit))		
			
	if args.description is not None:
		desc_str = ' '.join([str(token) for token in args.description])
		if len(desc_str) == 0 or re.match(blank_desc, desc_str):
			parser.error('Logbook description cannot be blank')
	
		if len(desc_str) > desc_limit:
			parser.error('Logbook description cannot exceed {} characters.'.format(desc_limit))
	else:	
		parser.error('Logbook description cannot be blank')

	print 'logbook_name: {}\nabbreviation: {}\ndescription: {}'.format(args.name, args.abbreviation, desc_str)
	
	status = elogutils.insert_elog_logbook(args.name, args.abbreviation, desc_str, args.restricted)

	if status == 1:
		exit(1)



if __name__ == '__main__':
	main()
