from threading import Thread
from enum import Enum
import time
import cv2 as cv
import pyautogui
from core.Logger import Logger
from core.Player import PLAYER_STATE

BG_STATUS = Enum('BG_STATUS', ['IDLE', 'IN_QUEUE', 'IN_BG', 'LOADING'])

class BattlegroundAgent:
  def __init__(self, monitor, player) -> None:
    self.battlegroundThread = None
    self.player = player
    self.logger = Logger("Battleground Agent")
    self.groupFinderIcon = cv.imread("assets/icons/GroupFinder.jpg", cv.IMREAD_GRAYSCALE)
    self.pvpTab = cv.imread("assets/" + player.lang + "/menus/PlayerVsPlayerTab.jpg", cv.IMREAD_GRAYSCALE)
    self.randomEpicBgButton = cv.imread("assets/" + player.lang + "/menus/RandomEpicBGButton.jpg", cv.IMREAD_GRAYSCALE)
    self.joinBattleButton = cv.imread("assets/" + player.lang + "/menus/JoinBattleButton.jpg", cv.IMREAD_GRAYSCALE)
    self.deserterIcon = cv.imread("assets/icons/Deserter.jpg", cv.IMREAD_GRAYSCALE)
    self.joinBgWindow = cv.imread("assets/" + player.lang + "/menus/JoinBGWindow.jpg", cv.IMREAD_GRAYSCALE)
    self.enterBgButton = cv.imread("assets/" + player.lang + "/menus/EnterBgButton.jpg", cv.IMREAD_GRAYSCALE)
    self.leaveBgButton = cv.imread("assets/" + player.lang + "/menus/LeaveMatchButton.jpg", cv.IMREAD_GRAYSCALE)
    self.status = BG_STATUS.IDLE
    self.monitor = monitor

  def startBGFarming(self):
    while self.player.state is PLAYER_STATE.BG_FARMING:
      self.player.checkConnection()
      self.status = BG_STATUS.IDLE
      if (self.isDeserter() is False):
        self.tagInBg()
      else:
        self.logger.log("Deserter debuff found, waiting for debuff to disapear before tagging to bg...")
      # self.inBgRoutine()
      time.sleep(3)

  def isDeserter(self):
    res = self.monitor.findMatch(self.deserterIcon)
    if (res == -1):
      return False
    return True

  def tagInBg(self):
    pyautogui.moveTo(50,50)
    self.logger.log("Tagging in random epic bg...")
    time.sleep(0.2)
    self.monitor.findMatchAndClickIfAvailable(self.groupFinderIcon)
    self.monitor.findMatchAndClickIfAvailable(self.pvpTab)
    self.monitor.findMatchAndClickIfAvailable(self.randomEpicBgButton)
    self.monitor.findMatchAndClickIfAvailable(self.joinBattleButton)
    self.status = BG_STATUS.IN_QUEUE
    self.waitForBg()
  
  def waitForBg(self):
    self.logger.log("Waiting for bg to start...")
    while self.status == BG_STATUS.IN_QUEUE:
      res = self.monitor.findMatch(self.joinBgWindow)
      if (res != -1):
        self.logger.log("Bg started joining the game...")
        self.monitor.findMatchAndClickIfAvailable(self.enterBgButton)
        self.status = BG_STATUS.LOADING
      time.sleep(1)
    self.inBgRoutine()
    

  def foundEndOfBg(self ):
    self.logger.log("End of bg detected, leaving...")
    self.status = BG_STATUS.IDLE
    time.sleep(10)

  def checkEndOfBg(self):
    self.monitor.findMatchAndClickIfAvailable(self.leaveBgButton, self.foundEndOfBg)

  def inBgRoutine(self):
    self.logger.log("BG in progress...")
    self.status = BG_STATUS.IN_BG
    while self.status == BG_STATUS.IN_BG:
      pyautogui.keyDown("up")
      self.checkEndOfBg()
      time.sleep(0.1)



  def run(self):
    self.logger.log("Starting battlegroung thread in 3 seconds...")
    time.sleep(1)
    self.logger.log("Starting battlegroung thread in 2 seconds...")
    time.sleep(1)
    self.logger.log("Starting battlegroung thread in 1 seconds...")
    time.sleep(1)
    
    self.battlegroundThread = Thread(
        target=self.startBGFarming, 
        args=(),
        name="battleground thread",
        daemon=True)
    self.battlegroundThread.start()