import sys
from socket import *
from datetime import datetime
import logging
import os
import time
import binascii
import requests


HOST = "127.0.0.1"
PORT = 50000
PATH = (
    r"D:\ГРАФИКА\БАСКЕТБОЛ\ЕДИНАЯ ЛИГА ВТБ 2022-2023\python\JSON\timer_basketball.json"
)

import socket

sock = socket.socket()
sock.bind(('', PORT))
sock.listen(1)
conn, addr = sock.accept()
print ('connected:', addr)

def send_data_CW(name, value):
    try:
        with socket.socket(AF_INET, SOCK_STREAM) as tcp_socket:
            tcp_socket.connect(('192.168.1.170', 5115))
            data = f"{name}={value}\n".encode()
            # print(f"Sending: {data}")  # Отладка
            tcp_socket.sendall(data)
            # print("Data sent!")  # Подтверждение отправки
    except Exception as e:
        print(f"Error sending TCP data: {e}")

def send_vmix(params):
    try:
        url = "http://192.168.1.240:8088/API/"
        requests.get(url, params=params)
    except Exception as ex:
        print(ex)

def parse(line, score1, score2):
    temp = line.split('#')
    diff1, diff2 = None, None
    t = temp[0]
    # for t in temp:
    if t not in [" ", ""]:
        a = t.split('/')
        print(a)
        timer_str = f"{a[4]}:{a[5] if len(a[5]) != 1 else f'0{a[5]}'}" if a[4] != "0" else f"{a[5]}.{a[6]}"
        timer_attack_str = a[2]
        points1 = a[7]
        points2 = a[8]
        quarter = a[13]
        if score1 != points1:
            diff1 = int(points1) - int(score1)
            score1 = points1
        if score2 != points2:
            score2 = points2
            diff2 = int(points2) - int(score2)

        fouls1 = a[9]
        fouls2 = a[10]
        path = r"D:\Графика\БАСКЕТБОЛ\FIBA"
        if int(fouls1) > 4:
            foul_pic1 = path + "\HOME-FOUL4.png"
        else:
            foul_pic1 = path + f"\HOME-FOUL{fouls1}.png"
        if int(fouls2) > 4:
            foul_pic2 = path + "\AWAY-FOUL4.png"
        else:
            foul_pic2 = path + f"\AWAY-FOUL{fouls2}.png"

        data = {
            "TIMER": timer_str,
            "ATTACK": timer_attack_str,
            "Score_Home": score1,
            "Score_Away": score2,
            "fouls1": fouls1,
            "fouls2": fouls2,
            "quarter": quarter,
        }

        send_data_CW("TIMER", data["TIMER"])
        send_data_CW("ATTACK", data["ATTACK"])
        send_data_CW("Score_Home", data["Score_Home"])
        send_data_CW("Score_Away", data["Score_Away"])
        send_data_CW("fouls1", data["fouls1"])
        send_data_CW("fouls2", data["fouls2"])
        send_data_CW("quarter", data["quarter"])

        params = {
            "Function": "SetText",
            "Input": 2,
            "SelectedName": "ATTACK.Text",
            "Value": data["ATTACK"],
            # "SelectedName": "TIME.Text",
            # "Value": timer_str,
        }
        send_vmix(params)
        params = {
            "Function": "SetText",
            "Input": 2,
            "SelectedName": "TIME.Text",
            "Value": data["TIMER"],
        }
        send_vmix(params)
        params = {
            "Function": "SetText",
            "Input": 2,
            "SelectedName": "SCORE1.Text",
            "Value": data["Score_Home"],
        }
        send_vmix(params)
        params = {
            "Function": "SetText",
            "Input": 2,
            "SelectedName": "SCORE2.Text",
            "Value": data["Score_Away"],
        }
        send_vmix(params)
        # params = {
        #     "Function": "SetText",
        #     "Input": 20,
        #     "SelectedName": "SCOREDIFF1.Text",
        #     "Value": f"+{diff1}",
        # }
        # requests.get(url, params=params)
        # params = {
        #     "Function": "SetText",
        #     "Input": 20,
        #     "SelectedName": "SCOREDIFF2.Text",
        #     "Value":  f"+{diff2}",
        # }
        # requests.get(url, params=params)

        params = {
            "Function": "SetImage",
            "Input": 2,
            "SelectedName": "FOULS_HOME.Source",
            "Value": foul_pic1,
        }
        send_vmix(params)
        params = {
            "Function": "SetImage",
            "Input": 2,
            "SelectedName": "FOULS_AWAY.Source",
            "Value": foul_pic2,
        }
        send_vmix(params)
        print(timer_str, timer_attack_str, points1, points2,fouls1, fouls2, diff1, diff2, a)
    return score1, score2


score1, score2 = 0, 0
while True:
    data = conn.recv(1024)
    line = data.decode("utf-8")
    print(line)
    if not data:
        break
    score1, score2 = parse(line, score1, score2)

conn.close()



    



# def main():
#     try:
#         tcp_socket = socket(AF_INET, SOCK_STREAM)
#         tcp_socket.connect((HOST, PORT))
#         data = str.encode("hello")
#         tcp_socket.send(data)
#         data = bytes.decode(data)
#         while True:
#             data = tcp_socket.recv(1024)
#             print(data)
#             # url = "http://127.0.0.1:8088/API/"
#             # params = {
#             #     "Function": "SetText",
#             #     "Input": 221,
#             #     "SelectedName": "12sec.Text",
#             #     "Value": timer_attack,
#             # }
#             # params1 = {
#             #     "Function": "SetColor",
#             #     "Input": 221,
#             #     "SelectedName": "12SecBackground.Fill.Color",
#             #     "Value": timer_color,
#             # }
#             # requests.get(url, params=params)
#     except KeyboardInterrupt:
#         tcp_socket.close()
#         sys.exit(1)


# if __name__ == "__main__":
#     main()
