import os
import time
import datetime
import mysql.connector 
import ftplib

import default_setting

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

def formatDate(date):
    if ((date == None) or (len(date) < 14)):
        date = "0000-00-00 00:00:00"
    else:
        dd = date[0:2]
        mm = date[3:5]
        yy = date[6:8]
        tm = date[9:14]
        date = '20'+yy+"-"+mm+"-"+dd+" "+tm+":00"
    return date

def ftpGetPart(connection):
    def writeline(data):   
        fd.write(data+'\n') 
#        fd.write(os.linesep)
     
    try:
#    environment =  'WMS_TESTOUT'
#        environment =  'KUK_TESTIN'  
        environment =  'WMS_TESTPART'  

        FTPSQL = "SELECT * FROM kuk_ftp WHERE env_name = '"+environment+"' limit 1"
        cursor = connection.cursor(dictionary=True)
        cursor.execute(FTPSQL) 
        FTPRow = cursor.fetchone()
        if FTPRow:
            BaaNHandShake = FTPRow['handshake_dir'];
            BaaNDir = FTPRow['BaaN_dir'];
            VimsDir = FTPRow['vims_dir'];
            VimsHandShake = FTPRow['vims_handshake'];
            readlock = FTPRow['read_lock_file'];
            writelock = FTPRow['write_lock_file'];
            FTP_HOST = FTPRow['ip_address'];
            FTP_USER = FTPRow['user_id'];
            FTP_PASS = FTPRow['password'];
        cursor.close()
# set-up ftp connection to iSeries
#        FTP_HOST = '172.92.5.3'
#        BaaNDir = 'WM#DTA'
#        FTP_USER = 'ca400'
#        FTP_PASS = 'ca400'
#        file_path = 'z:/input'
        
        print("FTP:",FTP_HOST,FTP_USER,FTP_PASS,BaaNDir)
        host_file = os.path.join(VimsDir, 'PARTS')
        ftp = ftplib.FTP(FTP_HOST)
        ftp.login(FTP_USER,FTP_PASS)
        ftp.cwd(BaaNDir)
        
        filename = 'PARTS'
        try:
            fd = open(host_file, 'wt')
            ftp.retrlines('RETR PARTS', writeline)
            fd.close()
        except Exception as e:
            print('FAIL-ftp error',e)
            pass 
        ftp.quit()
    except Exception as e:
        print ("FAIL-",e)
    return host_file
	
# timestamp value	
def getts():
    ts = time.time()
    ts = datetime.datetime.fromtimestamp(ts).strftime('_%Y%m%d_%H%M%S')
    return ts

def main():
    try:
# Default Connection / System Settings
        defaults = default_setting.defaultSettings()
# mySql Connector
        connection = mysql.connector.connect(user=defaults['dbuser'], password=defaults['dbpwd'],host=defaults['dbhost'],database=defaults['dbase'])
        
        print('ftpGetPart')
        file_path_map = ftpGetPart(connection)
    except Exception as e:
        print("FAIL-",str(e))
if __name__ == '__main__':
    main()
	
	