import os
import sys
import socket
import time
from time import sleep
from crccheck.crc import CrcArc
from datetime import datetime

# Signal Types
# Send with image: "SIA-DCS"0001L0#999

def sendSia(type, host, port):
    data = type.encode()
    crc = CrcArc.calc(data)
    crcstr = str(hex(crc)).split('x')
    crcstr = str(crcstr[1].upper())
    if len(crcstr) == 2:
        crcstr = '00' + crcstr
    if len(crcstr) == 3:
        crcstr = '0' + crcstr
    length = str(hex(len(data))).split('x')
    client_socket = socket.socket()
    client_socket.connect((host, port))
    client_socket.settimeout(10)
    text = '\u000A' + crcstr + '00' + length[1].upper() + type + '\u000D'
    print('Sent signal: ' + text)
    message = bytes(text, 'ASCII')
    client_socket.send(message)
    data = client_socket.recv(64).decode()
    print("Received from server: " + data)
    client_socket.close()

arg1 = sys.argv[1] if len(sys.argv) > 1 else None
arg2 = sys.argv[2] if len(sys.argv) > 2 else None
arg3 = sys.argv[3] if len(sys.argv) > 3 else None
host = sys.argv[4] if len(sys.argv) > 4 else None
arg5 = sys.argv[5] if len(sys.argv) > 5 else None
signalType = sys.argv[6] if len(sys.argv) > 6 else "PA"
zone = sys.argv[7] if len(sys.argv) > 7 else "00"
arg8 = sys.argv[8] if len(sys.argv) > 8 else ""
arg9 = sys.argv[9] if len(sys.argv) > 9 else "0"
arg10 = sys.argv[10] if len(sys.argv) > 10 else None
port = int(arg5)

def program():
    global host
    global port
    global arg1
    global arg2
    global arg3
    global signalType
    global zone
    global arg8
    global arg9
    global arg10
    current_time_milliseconds = int(time.time() * 1000)

    Zone = zone
    if len(Zone) == 1:
        Zone = "00" + Zone
    if len(Zone) == 2:
        Zone = "0" + Zone

    # convert timestamp to string in dd-mm-yyyy HH:MM:SS
    date_time = datetime.now()
    str_date_time = date_time.strftime("_%H:%M:%S,%d-%m-%Y")
    type = f'"ADM-CID"0000R00L0000#{arg1}[#{arg1}|{signalType} 00 {Zone}][V{arg10}?time={current_time_milliseconds}]{str_date_time}'
    sendSia(type, host, port)

program()
