#!/usr/bin/env python3
#=====================================================================================
# Get data from an XML file 
# Convert to a list of dictionaries Python object
# insert data into Oracle table
# *Below, update the name of the input file, and the table name 
#===================================================================================== 
import sys
import cgi                                 #cgi for web 
import cx_Oracle as oradb                  #import Oracle driver
 
sys.path.insert(0,'/home/s/sultans/web/python/demo/etl/util')
import oracle                              #import custom functions for Oracle
import fileIO                              #import custom functions for file I/O
import convert                             #import custom functions to convert format
import emailFunc                           #import custom function  to email
 
print("Content-Type: text/plain \n")       #required HTTP response header (w/ extra line) for web

infile     = '/home/s/sultans/web/python/demo/data/xml.txt'
db_name    = 'demo'
table_name = 'temp_table'

#===============================================================================================
# Main code
#===============================================================================================
xml          = fileIO.read(infile)                                #read the file
list_dict    = convert.xml2obj(xml)                               #convert XML to Python list of dictionaries
read_count   = len(list_dict)                                     #number of input lines
isSuccess    = oracle.dropTable(db_name,table_name)               #drop the table
isSuccess    = oracle.createTable(db_name,table_name,list_dict)   #create the table   
insert_count = oracle.insert(db_name,table_name,list_dict)        #insert into the table

if read_count == insert_count:
    print('DB insert successful,',insert_count,'rows affected')
else:
    print('DB insert error, read=',read_count,'insert=',insert_count)
    emailFunc.send("ss4922@nyu.edu",                                #send email from
                   "sam.sultan@hbo.com",                            #to   
                   "message subject",
                   "this is the body of the message") 

#===============================================================================================