# 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 excel_order
import asnupload
import vimsftp
import tt_ran_order
import tt_ran_allocate
import lr_order
import receipt
import receiptcsv
import order
import receiptidoc
import pickidoc
import idocout

def archive(file):
    file_path_archive = os.path.join(dir_path, '../vimsarchive/')

def main():
# get Upload Directories from company settings
    defaults = default_setting.defaultSettings()
    uploadDirs = default_setting.companySettings(defaults)
    
# no defaults
    if ((uploadDirs['interfacein'] == "") or (uploadDirs['interfacein'] == None)):
# Get OS
        # linux
        if platform == "linux" or platform == "linux2":
            pass
        # OS X
        elif platform == "darwin":
            pass
        # Windows...
        elif platform == "win32":
            uploadDirs['interfacein'] = '/rrfiles/input'
            uploadDirs['interfaceout'] = '/rrfiles/output'

#	print(uploadDirs['interfacein'])
    sys.stdout.write("\r")
    sys.stdout.write(uploadDirs['interfacein'])
    sys.stdout.flush()
# ---------------------------------------------------------------------------------------------------	
# Process Confirmed Receipts
# Create IDOCS & Flag Receipt Header
    receiptidoc.main()
    try:
# 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))
            shutil.copy(idoc, os.path.join("/rrfiles/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)
    except:
        pass
# ---------------------------------------------------------------------------------------------------	
# Process Confirmed Picks
# Create IDOCS & Flag Pick Header
    pickidoc.main()
    try:
# 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))
            shutil.copy(idoc, os.path.join("/rrfiles/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)
    except:
        pass
# ---------------------------------------------------------------------------------------------------			
# 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 iSeries Inteface Files	
    vimsftp.main()
# Create JSON Format
    file_path_in_txt = os.path.join(dir_path, '../vimsin/RJEIN*.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)
# 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
        lr_order.main()
        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()
        if os.path.exists(in_file):
            os.remove(in_file)
# populate Inventory with TT-RAN
    tt_ran_allocate.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 __name__ == '__main__':
    while True:
        main()
        sys.stdout.write("\r")
        sys.stdout.flush()
        dots = ".............................."
        for remaining in range(30, 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)
	
