"""Module providing a fishing agent."""

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

class FishingAgent:
  def __init__(self, monitor, player) -> None:
    self.fishingBobberImg = cv.imread("assets/fishing/bobbers/Bobber2.jpg", cv.IMREAD_GRAYSCALE)
    self.fishingIconImg = cv.imread("assets/fishing/FishIcon.jpg", cv.IMREAD_GRAYSCALE)
    self.fishingThread = None
    self.logger = Logger("Fishing Agent")
    self.monitor = monitor
    self.lureLoc = None
    self.player = player
    self.fail = 0
    self.retry = 0

  def startFishing(self):
    self.player.checkConnection()
    self.player.changeState(PLAYER_STATE.FISHING)
    while self.player.state is PLAYER_STATE.FISHING:
      if (self.fail > 5):
        self.fail = 0
        self.logger.log("Fishing failed too many times. Stopping fishing thread...")
        self.player.changeState(PLAYER_STATE.IDLE)
        return
      self.castLure()

  def castLure(self):
    self.retry = 0
    self.lureLoc = None
    pyautogui.moveTo(50,50)
    self.logger.log("Casting Lure.")
    res = self.monitor.findMatchAndMoveToPosition(self.fishingIconImg)
    if (res == -1):
      self.logger.log("Trying again in 1 second...")
      time.sleep(1)
      self.castLure()
    pyautogui.click()
    self.findLure()

  def findLure(self):
    self.logger.log("Moving cursor to Lure.")
    time.sleep(2)
    res = self.monitor.findMatch(self.fishingBobberImg)

    if (res == -1):
      if (self.retry > 4):
        self.fail += 1
        self.logger.log("Took too long to find lure, retrying fishing from the beginning")
        return
      else:  
        self.logger.log("Trying again in 1 second...")
        self.retry += 1
        time.sleep(1)
        self.findLure()
    time.sleep(0.5)
    self.lureLoc = res
    pyautogui.moveTo(self.lureLoc[0], self.lureLoc[1])
    self.watchLure()

  def watchLure(self):
    self.retry = 0
    self.logger.log("Waiting for fish...")
    while True:
      self.retry += 1
      time.sleep(0.1)
      res = self.monitor.findMatch(self.fishingBobberImg)
      print(self.lureLoc)
      print(res)
      if (res != -1 and abs(res[1] - self.lureLoc[1]) > 10):
        time.sleep(0.2)
        pyautogui.click()
        time.sleep(0.5)
        return
      elif (self.retry > 200):
        self.retry = 0
        self.fail += 1
        return

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