# Process Interface file.

import os
import sys
from sys import platform
import shutil
import glob
import time
import datetime

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

# Import VIMS .py
import default_setting
import idocin
import edi_order
import excel_order
import asnupload
import vimsftp
import vimsftpstonebranch
import vimsftpput
import tt_ran_order
import tt_ran_allocate
import lr_order
import receipt
import receiptcsv
import order
import receiptidoc
import pickidoc
import idocout
import transactionhistoryvendor
import orderpartid
import logfileappend
import logfileappendtext

def archive(file):
    file_path_archive = os.path.join(dir_path, '../vimsarchive/')

def main():
	# global switches for ftp & order
	ftpFlag = "N"
	orderFlag = "Y"
	ediOrderFlag = "Y"
	as400Flag = "N"
	# get Upload Directories from company settings
	defaults = default_setting.defaultSettings()
	uploadDirs = default_setting.companySettings(defaults)

	# Get OS
	# linux
	if platform == "linux" or platform == "linux2":
		pass
	# OS X
	elif platform == "darwin":
		pass
	# Windows...
	elif platform == "win32":
		pass
	#		uploadDirs['interfacein'] = 'c:/rrfiles/input'
	#		uploadDirs['interfaceout'] = 'c:/rrfiles/output'

	#	print(uploadDirs['interfacein'])
	sys.stdout.write("\r")
	sys.stdout.write(uploadDirs['interfacein'])
	sys.stdout.flush()
# ---------------------------------------------------------------------------------------------------	
# Process Confirmed Receipts
	if (1 != 1):
# Create IDOCS & Flag Receipt Header
		receiptidoc.main()
# Read IDOCS
		for idoc in glob.glob(os.path.join(dir_path, '../vimsin/rcp*.txt')):
# split out directory & filename
			path, fileName = os.path.split(idoc)
			file_path_in_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
			file_path_out_txt = os.path.join(dir_path, '../vimsout/idoctranout.txt')
			shutil.copy(idoc, file_path_in_txt)
# Archive
			shutil.copy(idoc, os.path.join(dir_path, '../vimsarchive/idoc_'+fileName))
# Network Folder for RRMC Vims
			shpName = "SHP"+fileName[3:]
			shutil.copy(idoc, os.path.join("r:/output/"+shpName))
# Format as SAP fixed-length text
			idocout.main()
			shutil.copy(file_path_out_txt, os.path.join(dir_path, '../vimsout/'+fileName))
#            shutil.copy(file_path_out_txt, os.path.join("\\\\172.16.1.193\\share\\rrfiles\\output\\"+fileName))
# Archive
			shutil.copy(file_path_out_txt, os.path.join(dir_path, '../vimsarchive/'+fileName))
# remove processed file
			if os.path.exists(idoc):
				os.remove(idoc)		
# ---------------------------------------------------------------------------------------------------	
# Process Confirmed Picks
	if (1 != 1):
# Create IDOCS & Flag Pick Header
		pickidoc.main()
# Read IDOCS
		for idoc in glob.glob(os.path.join(dir_path, '../vimsin/pck*.txt')):
# split out directory & filename
			path, fileName = os.path.split(idoc)
			file_path_in_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
			file_path_out_txt = os.path.join(dir_path, '../vimsout/idoctranout.txt')
			shutil.copy(idoc, file_path_in_txt)
# Archive
			shutil.copy(idoc, os.path.join(dir_path, '../vimsarchive/idoc_'+fileName))
# Network Folder for RRMC Vims
			pckName = "PCK"+fileName[3:]
			shutil.copy(idoc, os.path.join("r:/output/"+pckName))
# Format as SAP fixed-length text
			idocout.main()
			shutil.copy(file_path_out_txt, os.path.join(dir_path, '../vimsout/'+fileName))
#            shutil.copy(file_path_out_txt, os.path.join("\\\\172.16.1.193\\share\\rrfiles\\output\\"+fileName))
# Archive
			shutil.copy(file_path_out_txt, os.path.join(dir_path, '../vimsarchive/'+fileName))
# remove processed file
			if os.path.exists(idoc):
				os.remove(idoc)		
# ---------------------------------------------------------------------------------------------------			
# process IDOC PCKs from upload directory
	file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
	for pck in glob.glob(uploadDirs['interfacein']+"\\xxxPCK*.txt"):
# split out directory & filename
		path, fileName = os.path.split(pck)
# Archive
		shutil.copy(pck, os.path.join(dir_path, '../vimsarchive/'+fileName))
# Create JSON Format
		shutil.copy(pck, file_path_out_txt)
		idocin.main()
# Create JSON Format
		file_path_in_json = os.path.join(dir_path, '../vimsjson/idoctranout.json')
		for idoc in glob.glob(os.path.join(dir_path, '../vimsjson/idocmsgin*.json')):
			shutil.copy(idoc, file_path_in_json)
# Create / Update Order
			order.main()
# remove processed file
			if os.path.exists(idoc):
				os.remove(idoc)
			
		if os.path.exists(pck):
			os.remove(pck)
# ---------------------------------------------------------------------------------------------------						
# process IDOC ASNs from upload directory
	file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
	for asn in glob.glob(uploadDirs['interfacein']+"\\ASN*.txt"):
		print(asn)
# split out directory & filename
		path, fileName = os.path.split(asn)
# Archive
		shutil.copy(asn, os.path.join(dir_path, '../vimsarchive/'+fileName))
# Create JSON Format
		shutil.copy(asn, file_path_out_txt)
		idocin.main()
		# Create JSON Format
		file_path_in_json = os.path.join(dir_path, '../vimsjson/idoctranout.json')
		for idoc in glob.glob(os.path.join(dir_path, '../vimsjson/idocmsgin*.json')):
			shutil.copy(idoc, file_path_in_json)
# Create / Update Receipt
			receipt.main()
# remove processed file
			if os.path.exists(idoc):
				os.remove(idoc)
			
		receiptcsv.main()
				
		if os.path.exists(asn):
			os.remove(asn)
#		continue
# ---------------------------------------------------------------------------------------------------				
# process ASNs from upload directory
	file_path_xls = os.path.join(dir_path, '../vimsin/asn.xlsx')
	for asn in glob.glob(uploadDirs['interfacein']+"\\ASN*.xlsx"):
		print(asn)
		shutil.copy(asn, file_path_xls)
		asnupload.main()
		if os.path.exists(asn):
			os.remove(asn)
#		continue

# ---------------------------------------------------------------------------------------------------	
# Process NMUK Inteface Files	
	vimsftpstonebranch.main()
# Create JSON Format
	file_path_in_txt = os.path.join(dir_path, '../vimsin/*.*')
	file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
# loop through order*.txt files
	for in_file in glob.glob(file_path_in_txt):
# split out directory & filename
		path, fileName = os.path.split(in_file)
		if (fileName == "idoctranin.txt"):
			continue
		shutil.copy(in_file, file_path_out_txt)
# Archive
		shutil.copy(in_file, os.path.join(dir_path, '../vimsarchive/'+fileName))
# remap as JSON format
		logfileappendtext.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt','AS400 IN - '+str(in_file))
		idocin.main()
		time.sleep(2)
# remove processed file
		if os.path.exists(in_file):
			os.remove(in_file)
# Process LRO Message
	in_file = os.path.join(dir_path, '../vimsjson/LROMSGIN.json')
	if os.path.exists(in_file):
			os.remove(in_file)
	in_file = os.path.join(dir_path, '../vimsjson/lromsgin.json')
	if os.path.exists(in_file):
			os.remove(in_file)
	file_path_json = os.path.join(dir_path, '../vimsjson/LROMSGIN*.json')
	file_path_out = os.path.join(dir_path, '../vimsjson/lromsgin.json')
	for in_file in glob.glob(file_path_json):
# split out directory & filename
		path, fileName = os.path.split(in_file)
		if (in_file != file_path_out):
			try:
				shutil.copy(in_file, file_path_out)
			except:
				pass
		logfileappendtext.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt','LRO - '+str(in_file))
		lr_order.main()
		logfileappend.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt',in_file)
		if os.path.exists(in_file):
			os.remove(in_file)
# Process TTO Message
	in_file = os.path.join(dir_path, '../vimsjson/TTOMSGIN.json')
	if os.path.exists(in_file):
			os.remove(in_file)
	in_file = os.path.join(dir_path, '../vimsjson/ttomsgin.json')
	if os.path.exists(in_file):
			os.remove(in_file)
	file_path_json = os.path.join(dir_path, '../vimsjson/SUPPORDRMSGIN*.json')
	file_path_out = os.path.join(dir_path, '../vimsjson/ttomsgin.json')
	for in_file in glob.glob(file_path_json):
# split out directory & filename
		path, fileName = os.path.split(in_file)
		if (in_file != file_path_out):
			shutil.copy(in_file, file_path_out)
		tt_ran_order.main()
		logfileappend.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt',in_file)
		if os.path.exists(in_file):
			os.remove(in_file)
# populate Inventory with TT-RAN
	tt_ran_allocate.main()

	
# Process NMUK AS400 Inteface Files	
	if (as400Flag == "Y"):
		vimsftp.main()
# Create JSON Format
		file_path_in_txt = os.path.join(dir_path, '../vimsin/*.*')
		file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
# loop through order*.txt files
		for in_file in glob.glob(file_path_in_txt):
# split out directory & filename
			path, fileName = os.path.split(in_file)
			if (fileName == "idoctranin.txt"):
				continue
			shutil.copy(in_file, file_path_out_txt)
# Archive
			shutil.copy(in_file, os.path.join(dir_path, '../vimsarchive/'+fileName))
# remap as JSON format
			logfileappendtext.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt','AS400 IN - '+str(in_file))
			idocin.main()
			time.sleep(2)
# remove processed file
			if os.path.exists(in_file):
				os.remove(in_file)
# Process LRO Message
		in_file = os.path.join(dir_path, '../vimsjson/LROMSGIN.json')
		if os.path.exists(in_file):
				os.remove(in_file)
		in_file = os.path.join(dir_path, '../vimsjson/lromsgin.json')
		if os.path.exists(in_file):
				os.remove(in_file)
		file_path_json = os.path.join(dir_path, '../vimsjson/LROMSGIN*.json')
		file_path_out = os.path.join(dir_path, '../vimsjson/lromsgin.json')
		for in_file in glob.glob(file_path_json):
# split out directory & filename
			path, fileName = os.path.split(in_file)
			if (in_file != file_path_out):
				try:
					shutil.copy(in_file, file_path_out)
				except:
					pass
			logfileappendtext.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt','LRO - '+str(in_file))
			lr_order.main()
			logfileappend.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt',in_file)
			if os.path.exists(in_file):
				os.remove(in_file)
# Process TTO Message
		in_file = os.path.join(dir_path, '../vimsjson/TTOMSGIN.json')
		if os.path.exists(in_file):
				os.remove(in_file)
		in_file = os.path.join(dir_path, '../vimsjson/ttomsgin.json')
		if os.path.exists(in_file):
				os.remove(in_file)
		file_path_json = os.path.join(dir_path, '../vimsjson/SUPPORDRMSGIN*.json')
		file_path_out = os.path.join(dir_path, '../vimsjson/ttomsgin.json')
		for in_file in glob.glob(file_path_json):
# split out directory & filename
			path, fileName = os.path.split(in_file)
			if (in_file != file_path_out):
				shutil.copy(in_file, file_path_out)
			tt_ran_order.main()
			logfileappend.fileappend('c:/xampp/htdocs/vimslog/vimsupload.txt',in_file)
			if os.path.exists(in_file):
				os.remove(in_file)
# populate Inventory with TT-RAN
		tt_ran_allocate.main()
# ---------------------------------------------------------------------------------------------------
# FTP Put to Stonebranch server - from outout folder
	vimsftpput.main()
#				
# ---------------------------------------------------------------------------------------------------
				
# Create JSON Format
	file_path_in_txt = os.path.join(dir_path, '../vimsin/order*.txt')
	file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
# loop through order*.txt files
	for in_file in glob.glob(file_path_in_txt):
		shutil.copy(in_file, file_path_out_txt)
# split out directory & filename
		path, fileName = os.path.split(in_file)
# Archive
		shutil.copy(in_file, os.path.join(dir_path, '../vimsarchive/'+fileName))
# remap as JSON format
		idocin.main()
# remove processed file
		if os.path.exists(in_file):
			os.remove(in_file)
			
# move JSON files to interface output directory
	file_path_json = os.path.join(dir_path, '../vimsjson/order*.json')
	for in_file in glob.glob(file_path_json):
# split out directory & filename
		path, fileName = os.path.split(in_file)
		shutil.copy(in_file, uploadDirs['interfaceout']+"\\"+fileName)
		if os.path.exists(in_file):
			os.remove(in_file)
			
# ---------------------------------------------------------------------------------------------------
# Get All remaining files in upload Directory
	directory = uploadDirs['interfacein']			
	for fileName in os.listdir(directory):
		file_path = os.path.join(directory, fileName)
		if not os.path.isfile(file_path):
			continue
			
		print(file_path)
# Process pick-order excel Files to create .txt files
		file_path_xls = os.path.join(dir_path, '../vimsin/order.xlsx')
		if fileName.lower().endswith(('.xlsx', '.xls')):
# Copy & Rename File
			shutil.copy(file_path, file_path_xls)
# Format .xls data to .txt format
			excel_order.main()			
# Delete processed Input File
		if os.path.exists(file_path_xls):
			os.remove(file_path_xls)
		if os.path.exists(file_path):
			os.remove(file_path)
			
# ---------------------------------------------------------------------------------------------------	
	if (orderFlag == "Y"):
	# process orders from upload directory
		file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
		file_path_txt = os.path.join(dir_path, '../vimsin/order*.txt')
		for pck in glob.glob(file_path_txt):
	# split out directory & filename
			path, fileName = os.path.split(pck)
	# Create JSON Format
			shutil.copy(pck, file_path_out_txt)
			idocin.main()

			if os.path.exists(pck):
				os.remove(pck)	
# Create JSON Format
	file_path_in_json = os.path.join(dir_path, '../vimsjson/idoctranout.json')
	for idoc in glob.glob(os.path.join(dir_path, '../vimsjson/vimsormsgin*.json')):
		shutil.copy(idoc, file_path_in_json)
# Create / Update Order
		order.main()
# remove processed file
		if os.path.exists(idoc):
			os.remove(idoc)

# ---------------------------------------------------------------------------------------------------	
# process EDI orders from ORDERR directory
	if (ediOrderFlag == "Y"):
		file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
		for pck in glob.glob(uploadDirs['interfacein']+"/EDI_ORDERR/*.*"):
# split out directory & filename
			path, fileName = os.path.split(pck)
# Create JSON Format Files
			shutil.copy(pck, file_path_out_txt)
			edi_order.main()
# Process JSON ordermsgin Files
			file_path_in_json = os.path.join(dir_path, '../vimsjson/idoctranout.json')
			for idoc in glob.glob(os.path.join(dir_path, '../vimsjson/ordermsgin*.json')):
				shutil.copy(idoc, file_path_in_json)
# Create / Update Order
				order.main()
# remove processed file
				if os.path.exists(idoc):
					os.remove(idoc)
			if os.path.exists(pck):
				os.remove(pck)			
# ---------------------------------------------------------------------------------------------------	
# process orders from upload directory
	file_path_out_txt = os.path.join(dir_path, '../vimsin/idoctranin.txt')
	for pck in glob.glob(uploadDirs['interfacein']+"\\orders*.txt"):
# split out directory & filename
		path, fileName = os.path.split(pck)
# Create JSON Format
		shutil.copy(pck, file_path_out_txt)
		idocin.main()
# Create JSON Format
		file_path_in_json = os.path.join(dir_path, '../vimsjson/idoctranout.json')
		for idoc in glob.glob(os.path.join(dir_path, '../vimsjson/idocmsgin*.json')):
			shutil.copy(idoc, file_path_in_json)
# Create / Update Order
			order.main()
# remove processed file
			if os.path.exists(idoc):
				os.remove(idoc)
			
		if os.path.exists(pck):
			os.remove(pck)	
# ---------------------------------------------------------------------------------------------------
# populate vendor_code on transaction_history
	transactionhistoryvendor.main()
# populate order_body part_id
	orderpartid.main()
# ---------------------------------------------------------------------------------------------------																						
if __name__ == '__main__':
    while True:
        try:
            main()
        except Exception as err:
            print("INTERFACE ERROR -",str(err))
            time.sleep(5)
            pass
        try:    
            sys.stdout.write("\r")
            sys.stdout.flush()
            dots = "..........................................................."
            for remaining in range(60, 0, -1):
                dots = dots[0:remaining]+" "
                sys.stdout.write("\r")
                sys.stdout.write("{:2d} seconds remaining".format(remaining)+dots)
                sys.stdout.flush()
                time.sleep(1)
        except Exception as err:
            pass

	
