import pyautogui
import cv2
import mss
import numpy as np
from time import sleep

def printScreen():
    with mss.mss() as sct:
        monitor = sct.monitors[0]
        sct_img = np.array(sct.grab(monitor))
        # The screen part to capture
        # monitor = {"top": 160, "left": 160, "width": 1000, "height": 135}

        # Grab the data
        return sct_img[:,:,:3]

def getPosition(target, threshold=0.7,img = None):
    if img is None:
        img = printScreen()
    result = cv2.matchTemplate(img,target,cv2.TM_CCOEFF_NORMED)
    w = target.shape[1]
    h = target.shape[0]

    yloc, xloc = np.where(result >= threshold)


    rectangles = []
    for (x, y) in zip(xloc, yloc):
        rectangles.append([int(x), int(y), int(w), int(h)])
        rectangles.append([int(x), int(y), int(w), int(h)])

    rectangles, weights = cv2.groupRectangles(rectangles, 1, 0.2)
    return rectangles

def confirmWhatsapp():
    # Get the screen
    img = printScreen()
    # Load the target image
    target = cv2.imread('button.png')
    # Get the x,y,w,h of the target image
    rectangles = getPosition(target,0.8,img)
    # Click position of the target image
    if len(rectangles):
        x,y,w,h = rectangles[0]
        pyautogui.moveTo(x+w//2,y+h//2,duration=0.25)
        pyautogui.click()

def confirmMessage():
    # Get the screen
    img = printScreen()
    # Load the target image
    target = cv2.imread('message.png')
    # Get the x,y,w,h of the target image
    rectangles = getPosition(target,0.8,img)
    # Click position of the target image
    if len(rectangles):
        x,y,w,h = rectangles[0]
        pyautogui.moveTo(x+w//2,y+h//2,duration=0.25)
        pyautogui.click()

def clickMessagebox():
    # Get the screen
    img = printScreen()
    # Load the target image
    target = cv2.imread('messagebox.png')
    # Get the x,y,w,h of the target image
    rectangles = getPosition(target,0.8,img)
    # Click position of the target image
    if len(rectangles):
        x,y,w,h = rectangles[0]
        pyautogui.moveTo(x+w//2,y+h//2,duration=0.25)
        pyautogui.click()

def contactErr():
    # Repeat 2 times
    for i in range(2):
        # Press ESC to close the contact error popup
        pyautogui.press('esc')
        sleep(1)
        # Get the screen
        img = printScreen()
        # Load the target image
        target = cv2.imread('contacterr.png')
        # Get the x,y,w,h of the target image
        rectangles = getPosition(target,0.8,img)
        # Click position of the target image
        if len(rectangles):
            x,y,w,h = rectangles[0]
            pyautogui.moveTo(x+w//2,y+h//2,duration=0.25)
            pyautogui.click()

def checkButton(image):
    # Get the screen
    img = printScreen()
    # Load the target image
    target = cv2.imread(image)
    # Get the x,y,w,h of the target image
    rectangles = getPosition(target,0.8,img)
    # Click position of the target image
    if len(rectangles):
        return True
    return False

def clickButton(image):
    # Get the screen
    img = printScreen()
    # Load the target image
    target = cv2.imread(image)
    # Get the x,y,w,h of the target image
    rectangles = getPosition(target,0.8,img)
    # Click position of the target image
    if len(rectangles):
        x,y,w,h = rectangles[0]
        pyautogui.moveTo(x+w//2,y+h//2,duration=0.25)
        pyautogui.click()

def main():
    firstTime = True
    actionsTimer = 2
    while True:
        contactError = False
        # 40, 115 -> Agenda Reset
        if firstTime:
            pyautogui.moveTo(40, 115, duration=0.25)
            pyautogui.click()
            sleep(actionsTimer-1)
            firstTime = False
        # Check done.png
        if checkButton('done.png'):
            print('All contacts done!')
            break
        # Check if agenda list is open
        if checkButton('agenda.png'):
            clickButton('agenda.png')
            sleep(actionsTimer-1)
        # 355, 600 -> Click on first Person
        pyautogui.moveTo(355, 600, duration=0.25)
        pyautogui.click()
        sleep(actionsTimer-1)
        # 1430, 275 -> Click send with Whatsapp
        pyautogui.moveTo(1430, 275, duration=0.25)
        pyautogui.click()
        sleep(actionsTimer-1)
        # Find button.png to confirm Whatsapp
        confirmWhatsapp()
        sleep(actionsTimer-1)
        # Send Alt + Tab -> Back to browser
        pyautogui.hotkey('alt', 'tab')
        sleep(actionsTimer-1)
        # Find message.png to confirm message
        confirmMessage()
        sleep(actionsTimer+1)
        # Click on message box
        clickMessagebox()
        sleep(actionsTimer)
        # # Send Enter -> Send message
        # pyautogui.press('enter')
        # sleep(actionsTimer-1)
        # 615, 550 -> Click on Ok button
        # pyautogui.moveTo(615, 550, duration=0.25)
        # pyautogui.click()
        # sleep(actionsTimer)
        # Check if contact error
        if checkButton('contacterr.png'):
            contactError = True
            contactErr()
            sleep(actionsTimer)
        # Send Alt + Tab -> Back to browser
        pyautogui.hotkey('alt', 'tab')
        sleep(actionsTimer-1)
        # Send CTRL + W -> Close Whatsapp API tab
        pyautogui.hotkey('ctrl', 'w')
        sleep(actionsTimer-1)
        # 1485, 235 -> Click on success confirmation
        if contactError == False:
            # Click button contact-yes
            clickButton('contact-yes.png')
        if contactError == True:
            # Click button contact-no
            clickButton('contact-no.png')
        sleep(actionsTimer-1)
        # Sleep and repeat
        repeatTimer = 3
        print('Waiting ' + str(repeatTimer) + ' seconds ...')
        sleep(repeatTimer)

if __name__ == '__main__':
    main()