from PyQt5.QtWidgets import QDialog, QVBoxLayout, QTableWidgetItem, QMainWindow
from PyQt5 import uic
from pyqtgraph.Qt import QtGui
from PyQt5.QtGui import QTextCursor, QIcon
from Src.SocketCon import WebSocketWorker
from Src.Support import get_current_datetime_string
import pyqtgraph as pg
import time

class UI(QMainWindow):
    def __init__(self, activate_message):
        super(UI, self).__init__()
        uic.loadUi('./Ui/view.ui', self)
        self.setWindowIcon(QIcon('./Ui/icon.ico'))
        self.startBtn.clicked.connect(self.Start)
        self.stopBtn.clicked.connect(self.Stop)
        self.resetBtn.clicked.connect(self.Reset)

        with open('./Input/Setup.txt', 'r') as f:
            setup = f.read().split('\n')
        self.bet_array_input.setText(setup[0].replace('|', '\n'))
        self.tp_reset_input.setText(setup[1])
        self.sl_reset_input.setText(setup[2])
        self.tp_in.setText(setup[3])
        self.sl_in.setText(setup[4])

        self.expired_label.setText(f'Expired: {activate_message}')
        self.x = [0]
        self.y = [0]
        self.cl = [pg.mkPen('g', width=2)]
        self.plot_widget = pg.PlotWidget()
        self.picture = QtGui.QPicture()
        self.plot_data = pg.PlotDataItem(self.x, self.y, pen=pg.mkPen('g', width=2))
        self.plot_widget.addItem(self.plot_data)
        self.plot_widget.setBackground(QtGui.QColor('white'))
        self.chart_widget.setLayout(QVBoxLayout())
        self.chart_widget.layout().addWidget(self.plot_widget)
        self.plot_item = self.plot_widget.plot()
        self.plot_item.setDownsampling(auto=True)
        self.plot_item.setClipToView(True)
        self.countSent = 0
        self.countReceived = 0
        self.start = False
        self.rowcount = 0
        self.max_length = 500
        self.all_streak = {str(i): [0, 0] for i in range(32)}

    def UpdateStatus(self, status):
        if 'Error' in status:
            self.start = False
        self.statusLabel.setText(f'Status: {status}')

    def DisplayMessage(self, count, betPlace, player, banker, result, table_profit, profit, time_reset_win, time_reset_loss, streak, check_win):
        self.reset_time_label.setText(f'Time reset bet (win/loss): {time_reset_win} / {time_reset_loss}')
        self.update_streak_table(streak, check_win)
        if count is not None and betPlace is not None:
            rowPosition = self.resultTable.rowCount()
            if rowPosition >= self.max_length:
                self.resultTable.removeRow(0)
                self.rowcount += 1
            else:
                self.rowcount = rowPosition
            rowPosition = self.resultTable.rowCount()
            self.resultTable.insertRow(rowPosition)
            item = QTableWidgetItem(str(self.rowcount + 1))
            self.resultTable.setVerticalHeaderItem(rowPosition, item)
            self.resultTable.setItem(rowPosition, 0, QTableWidgetItem(str(count)))
            self.resultTable.setItem(rowPosition, 1, QTableWidgetItem(str(betPlace)))
            self.resultTable.setItem(rowPosition, 2, QTableWidgetItem(player))
            self.resultTable.setItem(rowPosition, 3, QTableWidgetItem(banker))
            self.resultTable.setItem(rowPosition, 4, QTableWidgetItem(str(result)))
            self.resultTable.setItem(rowPosition, 5, QTableWidgetItem(str(table_profit)))
            self.resultTable.setItem(rowPosition, 6, QTableWidgetItem(str(profit)))
            self.resultTable.setItem(rowPosition, 7, QTableWidgetItem(get_current_datetime_string()))
            self.resultTable.scrollToBottom()
            self.add_value(profit)
            end_time = time.time()
            total_duration = end_time - self.start_time
            minutes = int(total_duration // 60)
            seconds = int(total_duration % 60)
            self.time_run_label.setText(f'Time run: {minutes}:{seconds}')

    def update_streak_table(self, col: int, check_win: int):
        if col == 100 or check_win == 0:
            return
        if col <= 31:
            ind = col if check_win == 1 else col - 1
        else:
            ind = 31
        if check_win == 1:
            self.all_streak[str(ind)][0] += 1
        elif check_win == 2:
            self.all_streak[str(ind)][1] += 1
        item = QTableWidgetItem(f'{self.all_streak[str(ind)][0]}/{self.all_streak[str(ind)][1]}')
        self.streak_table.setItem(0, ind, item)

    def add_value(self, new_value):
        self.y.append(new_value)
        self.x.append(len(self.x))
        if len(self.y) > 1:
            last_value = self.y[-2]
            pen_color = 'g' if new_value > 0 else 'b' if new_value == last_value else 'r'
            self.cl.append(pg.mkPen(pen_color, width=2))
        for item in self.plot_widget.items():
            if isinstance(item, pg.InfiniteLine):
                self.plot_widget.removeItem(item)
        if self.enable_chart.isChecked():
            self.plot_widget.plot([self.x[-2], self.x[-1]], [self.y[-2], self.y[-1]], pen=self.cl[-1])
            y_min, y_max = min(self.y), max(self.y)
            min_line = pg.InfiniteLine(pos=y_min, angle=0, pen=pg.mkPen(color='r', width=2))
            max_line = pg.InfiniteLine(pos=y_max, angle=0, pen=pg.mkPen(color='g', width=2))
            avg_line = pg.InfiniteLine(pos=0, angle=0, pen=pg.mkPen(color='b', width=2))
            self.plot_widget.addItem(min_line)
            self.plot_widget.addItem(max_line)
            self.plot_widget.addItem(avg_line)
            self.plot_widget.autoRange()
        else:
            self.plot_widget.clear()

    def get_checkbox_value(self):
        with open('./Input/AllTable.txt', 'r') as f:
            tableID = [t.strip().split('|') for t in f.read().split('\n') if t.strip() != '']
        all_checkbox = [getattr(self, attr) for attr in dir(self) if attr.startswith('checkBox_')]
        all_id_selected = []
        for checkbox in all_checkbox:
            checkbox_name = checkbox.text()
            if checkbox.isChecked():
                for ti in tableID:
                    if checkbox_name == ti[1]:
                        table_id = ti[0]
                        all_id_selected.append(table_id)
                        print(f'{checkbox_name}: {table_id}')
        return all_id_selected

    def LogMessage(self, message):
        cursor = self.textEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        if self.textEdit.document().blockCount() >= 200:
            cursor.movePosition(QTextCursor.Start)
            for _ in range(self.textEdit.document().blockCount() - 199):
                cursor.movePosition(QTextCursor.StartOfBlock)
                cursor.movePosition(QTextCursor.EndOfBlock, QTextCursor.KeepAnchor)
                cursor.removeSelectedText()
        cursor.insertText(message + '\n')
        self.textEdit.ensureCursorVisible()

    def Start(self):
        try:
            self.start = True
            self.start_time = time.time()
            websocketUrl = self.linkIn.text().strip()
            if not websocketUrl:
                raise ValueError("WebSocket bağlantı adresi boş.")

            bet_array = [round(float(bv), 1) for bv in self.bet_array_input.text().split(',') if bv.strip() != '']
            if not bet_array:
                raise ValueError("Bahis dizisi boş veya hatalı formatta.")

            tp_reset = int(self.tp_reset_input.text())
            sl_reset = int(self.sl_reset_input.text()) * -1
            tp = int(self.tp_in.text())
            sl = int(self.sl_in.text()) * -1
            all_table_checked = self.get_checkbox_value()
            if not all_table_checked:
                raise ValueError("Hiçbir masa seçilmedi.")

            up_type = 1 if self.win_check_value.isChecked() else 2 if self.loss_check_value.isChecked() else 3 if self.both_check_value.isChecked() else 0

            self.statusLabel.setText('Status: Running')
            self.time_start_label.setText(f'Time start: {get_current_datetime_string()}')

            print(f"[INFO] WebSocket URL: {websocketUrl}")
            print(f"[INFO] Bet array: {bet_array}")
            print(f"[INFO] Tables: {all_table_checked}")
            print(f"[INFO] TP: {tp}, SL: {sl}, Reset TP: {tp_reset}, Reset SL: {sl_reset}")

            self.websocketWorker = WebSocketWorker(websocketUrl, bet_array, tp, sl, tp_reset, sl_reset, all_table_checked, up_type)
            self.websocketWorker.result_message.connect(self.DisplayMessage)
            self.websocketWorker.respone_message.connect(self.LogMessage)
            self.websocketWorker.status_updated.connect(self.UpdateStatus)
            self.websocketWorker.start()

        except Exception as e:
            error_msg = f"[ERROR] Başlatma sırasında hata oluştu: {e}"
            print(error_msg)
            self.LogMessage(error_msg)
            self.statusLabel.setText('Status: Error')

    def Reset(self):
        self.start = True
        self.resultTable.setRowCount(0)
        self.plot_widget.clear()
        self.x = [0]
        self.y = [0]
        self.cl = [pg.mkPen('g', width=2)]
        self.Start()

    def Stop(self):
        self.start = False
        self.websocketWorker.stop()
        self.statusLabel.setText('Status: Stopped')
