from websocket import create_connection
from PyQt5.QtCore import QThread, pyqtSignal
import json
import sys
import os
import ssl
from Src.Predict import Predict, LoadHistory
from Src.Support import GetTimestamp, generate_random_string, GetReplyId

class WebSocketWorker(QThread):
    result_message = pyqtSignal(str, str, str, str, str, float, float, int, int, int, int)
    respone_message = pyqtSignal(str)
    status_updated = pyqtSignal(str)
    balance = 0
    idUpdate = ''
    ableBet = False
    highestPoint = 0

    with open('./BetAction/RequestBet.json', 'r+') as betAction0:
        requestBet = json.loads(betAction0.read())
    with open('./Input/Strategy.txt', 'r+') as betAction1:
        preString = betAction1.read().split('\n')
    prediction = [p.strip().split('-') for p in preString if p.strip() != '']
    with open('./BetAction/Subscribe.json', 'r+') as betAction2:
        subscribeTable = json.loads(betAction2.read())

    multipleBet = []

    def __init__(self, url, baseBet, tp, sl, tp_reset, sl_reset, all_table_checked, up_type):
        super().__init__()
        self.url = url
        self.ws = None
        self.is_connected = False
        self.message_count_sent = 0
        self.message_count_received = 0
        self.baseBet = baseBet
        self.bet = baseBet
        self.profit = 0
        self.bets = 0
        self.wins = 0
        self.losses = 0
        self.ties = 0
        self.tp_reset = tp_reset
        self.sl_reset = sl_reset
        self.tp = tp
        self.sl = sl
        self.all_table_checked = all_table_checked
        self.up_type = up_type

    def run(self):
        try:
            self.ws = None
            for _ in range(10):
                try:
                    self.ws = create_connection(self.url)
                    break
                except:
                    try:
                        ca_file = ssl.create_default_context()
                        self.ws = create_connection(self.url, sslopt={'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': ca_file})
                        break
                    except:
                        pass
            self.is_connected = True
            if self.ws:
                self.status_updated.emit('Connected')
            else:
                self.status_updated.emit('Timeout')

            # Devamı aynı şekilde buraya yazılabilir...

        except Exception as e:
            excType, excObj, excTb = sys.exc_info()
            fname = os.path.split(excTb.tb_frame.f_code.co_filename)[1]
            err = str(excType) + '-' + str(fname) + '-' + str(excTb.tb_lineno)
            self.status_updated.emit(f'Error: {e} ({err})')
            self.is_connected = False

    def send_message(self, message):
        if self.is_connected:
            self.ws.send(message.replace("'", '"'))
            self.message_count_sent += 1
        else:
            self.status_updated.emit('Not connected')

    def reset_score(self):
        self.multipleBet = []

    def stop(self):
        self.is_connected = False
        if self.ws:
            self.ws.close()
