# Create Order interface file from EDI ORDERR order files.

import os
import time
import datetime
import json
from collections import OrderedDict 

import default_setting

# Get Current Path
dir_path = os.path.dirname(os.path.realpath(__file__))

def formatJson(orderStr):
#    print("formatJson")
# Create JSON Message Format
    ref = ""
    l = 0
    i = 0
    e = 0
    jsonMain = OrderedDict()
    jsonMain.clear()
    count = 0
# Split-out Message Segments
    lines = orderStr.split(",")
    for line in lines:
        count=count+1
#        print("count",count)
# seperate segments
        segments = line.split(";")
        if len(segments) > 0 and len(segments[0]) > 0:
# key & value
            key = segments[0].split(":")[1]
#            print("KEY:",key)
            if key == "E2LTORH":
                key = "vimsorderHeader"
            elif key == "Z2LTORH":
                key = "vimsorderBody"
            elif key == "E2LTORI":
                key = "vimsorderBody"
            elif key == "HD":
                key = "vimsorderHeader"
            elif key == "DT":
                key = "vimsorderBody"
            elif key == "FT":
                key = "vimsorderFooter"
# Call Function to Format to JSON
            if segments[0].split(":")[0].lower() != "segnam" or (segments[0].split(":")[0].lower() == "segnam" and len(segments) > 1):
                e = 0
                status = "new"
# if key is Blank add to Main Segment
                if key == "":
                    for segment in segments:
                        try:
                            jsonMain[segment.split(":")[0]] = segment.split(":")[1]
                        except:
                            pass
                else:
# Create Associative Dictionary for JSON segment
                    jsonSegment = OrderedDict()
                    jsonSegment.clear()
                    for segment in segments:
                        try:
                            if (segment.split(":")[0] == "customerReference"):
                                ref = segment.split(":")[1]
                                jsonSegment[segment.split(":")[0]] = ""
                            elif (segment.split(":")[0] == "expectedDate"):
                                date = segment.split(":")[1].replace('$',':')
                                jsonSegment[segment.split(":")[0]] = date
                            else:
                                jsonSegment[segment.split(":")[0]] = segment.split(":")[1]
                        except:
                            pass
# Add Segment to Main JSON
                    if status == "new":
                        if key not in jsonMain:
                            if key == "nmukbporBody":
                                jsonMain[key] = [jsonSegment]
                            elif key == "vimsorderBody":
                                jsonMain[key] = [jsonSegment]
                            else:
                                jsonMain[key] = jsonSegment
#                                    print("TEST1"+str(jsonMain)+"-"+str(segment))
                        elif type(jsonMain[key]) == list:
                            jsonMain[key].append(jsonSegment)
#                                print("TEST2"+str(jsonMain)+"-"+str(segment))
                        elif key == "nmukbporBody":
                            jsonMain[key] = [jsonMain[key], jsonSegment]
                        elif key == "vimsorderBody":
                            jsonMain[key] = [jsonMain[key], jsonSegment]
#                                print("TEST3"+str(jsonMain)+"-"+str(segment))
                        else:
                            jsonMain[key] = [jsonMain[key], jsonSegment]
#                                print("TEST4"+str(jsonMain)+"-"+str(segment))
                    else:
                        if key not in jsonMain:
                            jsonMain[key] = jsonSegment
                        elif type(jsonMain[key]) == list:
                            jsonMain[key].append(jsonSegment)
                        else:
                            try:
                                del jsonSegment['SEGNAM']
                            except:
                                pass
                            jsonMain[key].update(jsonSegment)

    print("JSON:"+json.dumps(jsonMain, ensure_ascii=False, indent=2))
# Create Message File
    ts = time.time()
    ts = datetime.datetime.fromtimestamp(ts).strftime('_%Y%m%d_%H%M%S_')
    l = l+1
    segmentType = "order"
    jsonFile = segmentType.strip()+"msgin"+ref+".json"
    file_path_json = os.path.join(dir_path, '../vimsjson/'+jsonFile)
    with open(file_path_json, "w") as write_file:
        json.dump(jsonMain, write_file, indent=2)
    jsonMain.clear()
    try:
        if (jsonSegment):
            del jsonSegment
    except:
        pass
    if (jsonMain):
        del jsonMain	
    return True

def getts():
    ts = time.time()
    ts = datetime.datetime.fromtimestamp(ts).strftime('_%Y%m%d_%H%M%S')
    return ts
	
def main():
# HDVIMSOR	:0065:SEGNAM;0000;0002;header;HDRREF;0018;0010;customerReference;DATE;+;0019;expectedDate;DEST;+;0010;destination;TYPE;+;0010;orderType
# DTVIMSOR	:0056:SEGNAM;0000;0002;body;PART;0002;0015;partNumber;QTY;+;0008;expectedQty;RANORDER;+;0015;ranOrder;ORDLN;+;0006;orderLine
# FTVIMSOR	:0012:SEGNAM;0000;0002;footer
    try:
        updated = False
        process = False
# Default Connection / System Settings
        defaults = default_setting.defaultSettings()
        line_count = 0
        customerRef = ""
        partNumber = ""
        dateTime = ""
        headerStr = ""
        bodyStr = ""
        footerStr = ""
        orderLine = 0
# Read Transaction
        file_path = os.path.join(dir_path, '../vimsin/idoctranin.txt')
        iDocTran = open(file_path,"r")
# Read lines from the input message file - for each line:
        for line in iDocTran:
            line = line.replace('\n','')
            line = line.replace(',','')
            line = line.replace("'",'')
#            print("Line:",line)
            row = line.split("+")
#            print("ROW:",row[0])
            try:
                if (row[0] == "UNB"):
                    continue
                if (row[0] == "UNH"):
                    if (row[1][0:6] == "ORDERR"):
                        if (process == True and headerStr != ""):
                            ordrStr = "HD:HD;"+headerStr+",DT:DT;"+bodyStr+",FT:FT;"+footerStr
                            jsonFormat(orderStr)
                            orderLine = 0
                        if len(headerStr) > 0:
                            headerStr = headerStr+";"
                        headerStr += "customerReference:"+row[1][6:]
#                        headerStr += "customerReference:"
                        process = True 
                if (row[0] == "MID"):
                    continue
                if (row[0] == "DAN"):
                    if (row[1] == ":ADVICE NOTE"):
                        if len(headerStr) > 0:
                            headerStr = headerStr+";"
#                        headerStr += "customerReference:"+row[2]
                        headerStr += ";orderType:STD"
                        if len(bodyStr) > 0:
                            bodyStr = bodyStr+";"
                        bodyStr += ";ranOrder:"+row[2]
                if (row[0] == "MSD"):
# CR=Create,RP=Replacement,AM=Amend,CC=Cancel
                    if len(bodyStr) > 0:
                        bodyStr = bodyStr+";"
                    if (row[1] == "CC"):
                        bodyStr += "status:C"
                    else:
                        bodyStr += "status:A"
                if (row[0] == "SDT"):
                    if len(headerStr) > 0:
                        headerStr = headerStr+";"
                    headerStr += "vendorCode:"+row[1]
                    if len(bodyStr) > 0:
                        bodyStr = bodyStr+";"
                    bodyStr += "vendorCode:"+row[1]
                if (row[0] == "BDT"):
                    if len(headerStr) > 0:
                        headerStr = headerStr+";"
                    headerStr += "destination:"+row[1][2:]
                if (row[0] == "ART"):
                    if len(bodyStr) > 0:
                        bodyStr = bodyStr+";"
                    bodyStr += "partNumber:"+row[2].split(':')[0]
                    orderLine = orderLine+1
                    bodyStr += ";orderLine:"+str(orderLine)
                if (row[0] == "DLV"):
                    if len(bodyStr) > 0:
                        bodyStr = bodyStr+";"
                    bodyStr += "expectedQty:"+row[2].split(':')[0]
                if (row[0] == "DTP"):
                    if len(headerStr) > 0:
                        headerStr = headerStr+";"
                    date,time = row[1].split(':')
                    headerStr += "expectedDate:20"+date[0:2]+"-"+date[2:4]+"-"+date[4:6]+" "+time[0:2]+"$"+time[2:4]+"$00"
#                    headerStr += "date:20"+date
#                    headerStr += ";time:"+time+"00"
                if (row[0] == "PIN"):
                    continue
                if (row[0] == "TCO"):
                    continue
                if (row[0] == "CSG"):
                    dns = row[1]
                    dock = row[2]
                    dock1 = row[3]
                if (row[0] == "UNS"):
                    continue
                if (row[0] == "UNT"):
#                    if (process == True and headerStr != ""):
                    orderStr = "HD:HD;"+headerStr+",DT:DT;"+bodyStr+",FT:FT;"+footerStr
#                    print("Test",detailStr)
                    formatJson(orderStr)
                    orderLine = 0
                    process = False
            
            except Exception as err:
                print("ERROR:",err)	
        try:
            os.remove(file_path_edi)
        except:
            pass
        return updated
            
    except Exception as err:
        print("ERROR:",err)
        return False
        
if __name__ == '__main__':
	main()