# Extract NMUK Interface Files from iSeries Server

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 ftpGetPickParms(connection):
    try:
#    environment =  'WMS_TESTOUT'
        environment =  'WMS_TESTIN'
#    $environment =  'KUK_LIVEIN'  

        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'];
        else:
            FTP_HOST = '172.92.5.3'
            BaaNDir = 'WM#DTA'
            FTP_USER = 'ca400'
            FTP_PASS = 'ca400'
            file_path = 'z:/input'
        cursor.close()

        host_file = os.path.join(file_path, 'pickplan.txt')
        ftp = ftplib.FTP(FTP_HOST)
        ftp.login(FTP_USER,FTP_PASS)
        ftp.cwd(BaaNDir)

def connect():
# get Upload Directories from company settings
    defaults = default_setting.defaultSettings()
    uploadDirs = default_setting.companySettings(defaults)
    print(uploadDirs['interfacein'])

def ftpGetList(host,user,password,dir,filter):
    ftp = ftplib.FTP(host)
    ftp.login(user,password)
    ftp.cwd(dir)
    filenames = ftp.nlst(filter+'*.*')
    ftp.quit()
    return filenames

def ftpGet(host,user,password,dir,remoteFile,localFile):
    ftp = ftplib.FTP(host)
    ftp.login(user,password)
    ftp.cwd(dir)
    try:
        with open(host_file, 'wb') as local_file:
                ftp.retrbinary('RETR ' + remoteFile, local_file.write)
                ftp.delete(filename)
        except ftplib.error_perm:
            pass 
    ftp.quit()
def main():
# set-up ftp connection to iSeries 
    host = '172.92.5.3'
    user = 'ca400'
    password = 'ca400'
    dir = 'KUKVIMSOUT'
    
    tranList = ['GRN','TOPICK']
    for transaction in tranList:
        files = ftpGetList(host,user,password,dir,transaction)
        for file in files:
            ftpGet(host,user,password,dir,file)
        
    

#loop through list of interface files
	file_path = os.path.join(dir_path, '../vimsin')
	for filename in filenames:
		host_file = os.path.join(file_path, filename)
		try:
			with open(host_file, 'wb') as local_file:
				ftp.retrbinary('RETR ' + filename, local_file.write)
				ftp.delete(filename)
		except ftplib.error_perm:
			pass 
	ftp.quit()
	
if __name__ == '__main__':
	main()