#Copyright © 2024 – WildGate Consultancy Solutions Limited – all Rights Reserved
#Proof of concept to constantly capture image from mapserver
#
#  *****************************************************************************************
#  *****************************************************************************************
#  24 Oct 24 - Tested and worked with NODE rED QR Code from https://nodered.securemapview.com/ui
#   
#  all clicks correct , note need to click on Advanced and proceed as site comes back as http
#
#   See TWOK Copy at  E:\Python311\Garrison\CaptureNRQRViaGarrisonTWOK-24Oct24
#
#  ************************************************************************************************
#    ********************************************************************************************
#
#
#
#  9 Oct 24 trying to access Node Red Ui 
#16 Jul 24 - ameded to work with new Garrison front end - using xpath to find elements
#6 Feb 24 - webdriver code updated and streamlit added to stream
# 
#20 Jul 23 .  Moved to 3.11,  options changed TWOK - Opens Garrison , find correct wondows mand elements, then actions clicks
#and adds link to map and opens map
#
# to run with streamlit  - streamlit run E:\Python311\Garrison\CaptureStreamViaGarrisonTest-Jul24.py
# then  open on      localhost:8501  or IP address 8501

cursor_script = '''
var cursor = document.createElement('div');
cursor.style.position = 'absolute';
cursor.style.zIndex = '9999';
cursor.style.width = '10px';
cursor.style.height = '10px';
cursor.style.borderRadius = '50%';
cursor.style.backgroundColor = 'red';
cursor.style.pointerEvents = 'none';
document.body.appendChild(cursor);

document.addEventListener('mousemove', function(e) {
  cursor.style.left = e.pageX - 5 + 'px';
  cursor.style.top = e.pageY - 5 + 'px';
});
'''

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options

from selenium.webdriver.chrome.service import Service as ChromeService  # added 25/1/24
from webdriver_manager.chrome import ChromeDriverManager # added 25/1/24


from selenium.webdriver.common.keys import Keys

#import streamlit as st # added 30 Jan 24

import time
from time import sleep
import cv2
import threading
#import pyautogui
#import mouse


def access_ultra():

    def user_input(driver):
        print ('s to skip')
        print (' m to maximise window')
        print (' r for low res retry')
        print (' R for low res retry')
        print (' p for resome from paused')
        print (' l to list windows')
        print (' u to list popups')
        print (' e to list elements')
        print (' ')
        val = input('select menu option or s to skip')
        if val == 'l':
            list = driver.window_handles
            print (list)
            #buttons = driver.find_elements(By.CSS_SELECTOR,"input[type='button']")
            elements = driver.find_elements(By.XPATH,'//*[@id]')
            #buttons = driver.find_elements_by_xpath(".//form//input[@type='button']")
            print(elements)
        if val == 'u':
            list = driver.window_handles
            print (list)
            #buttons = driver.find_elements(By.CSS_SELECTOR,"input[type='button']")
            popups = driver.find_elements(By.XPATH, '//div[@id="msg" and @style!=""]')
            #buttons = driver.find_elements_by_xpath(".//form//input[@type='button']")
            print(popups)			
			#(By.XPATH, '//div[@id="msg" and @style!=""]')
        if val == 'r':
            action = webdriver.common.action_chains.ActionChains(driver) 
            action.move_by_offset(550,400)  # this is from 0, 0 as new window
            print('clicking 550,400')
            action.click()
            action.perform()
            sleep(1)
        if val == 'R':
            action = webdriver.common.action_chains.ActionChains(driver) 
            action.move_by_offset(950,700)  # this is from 0, 0 as new window
            print('clicking 950,700')
            action.click()
            action.perform()
            sleep(1)
        if val == 'p':
            list = driver.window_handles
            print (list)
            driver.switch_to.window(list[1])
            sleep(1)
            sleep(0.5)
            action = webdriver.common.action_chains.ActionChains(driver) 
            action.move_by_offset(400,365)  # this is from 0, 0 as new window  
            print('clicking 400,365')            
            action.click()
            action.perform()
            sleep(2)
			
        if val == 'q':	
            print('closing driver...') 
			
            driver.switch_to.window(list[0])
            sleep(1)
            action = webdriver.common.action_chains.ActionChains(driver) 
            action.move_by_offset(1890,22)  # try to close broswer
            action.click()
            action.perform()
            sleep(2)
            driver.close()
            sleep(2)
			
        if val == 's':	
            pass
    
    
    options = Options()
    #options.headless = True  # remed out 25/1/24
    options.add_argument("window-size=1920,1000") # remed out 25/1/24
    options.add_argument("--headless")  # added 25/1/24
    options.add_argument('--no-sandbox')  # added 25/1/24
    options.add_argument('--disable-dev-shm-usage')  # added 25/1/24
    options.add_argument("--disable-web-security");  # added 28 Oct 24
    options.add_argument("--disable-popup-blocking");  # added 28 Oct 24
    options.add_experimental_option("useAutomationExtension", False) #added 6 Feb 24 - removes "Chrome is being controlled ..."
    options.add_experimental_option("excludeSwitches",["enable-automation"])  #added 6 Feb 24 - removes "Chrome is being controlled ..."
    #options.add_experimental_option('excludeSwitches', ['disable-popup-blocking']) # added 29 Oct 24

    count = 0
    driver = webdriver.Chrome(options=options)  #  added 9 Oct 24 - note was this before Jna 24 !!!
    screen = threading.Thread(target=screenshot, args=(driver,count))
    screen.start()
    
    #url = "https://www.google.com/"
    #url = "https://freeboard.io/"                                     
    #url = "http://209.38.235.136:8501"
    #url = "http://134.209.236.202:1880/tak-map"
    #url1 = "http://134.209.236.202:1880/Secondmap"
    #url = "https://live.garrison-ultra.com/login/"
    url = "https://002158.garrison-ultra.com/"
    #driver = webdriver.Chrome(options=options)
    #target = "http://134.209.236.202:1880/ui"
    target = "https://nodered.securemapview.com/ui"


    #driver1 = webdriver.Chrome(options=options)

    driver.get(url)
    #driver1.get(url1)
    sleep(1)


    #From main window select logon windon , entery key and submit

    curwin = driver.current_window_handle
    print (curwin)
    list = driver.window_handles
    print (list)

    #driver.switch_to.window(list[0])
    #driver.maximize_window()

    print('going to wait 1 secs')
    sleep(1)

    try:
        cont = driver.find_element(By.XPATH, '//html/body/div/div/form/div[2]/button[normalize-space()="Continue with an access key"]').click()    
        print(cont)
        print('found continue button')
        driver.save_screenshot('ss.png')
            
    except:
        print('continue button field not found')
        
    print('going to wait 2 secs')
    sleep(1)    
        

    logon = driver.find_element(By.XPATH, '//html/body/div/div/form/div[1]/div[2]/input').send_keys("kzVgqNQkQvuHYaup303POAvW6nxcK0s_ho78QG91PMzBVEymROxF75H0EPekvC_8")
    sleep(1)
    #
    signin = driver.find_element(By.XPATH, '//html/body/div/div/form//div[2]/button[1]').click()
    # kzVgqNQkQvuHYaup303POAvW6nxcK0s_ho78QG91PMzBVEymROxF75H0EPekvC_8 # updated Jul 24

    print('Keys entered')
    # 



    #switch back to main frame
    print('going to wait 1 secs')
    sleep(1)

    #list = driver.window_handles
    #print (list)
	
    list = []
    while len(list) < 2:
        list = driver.window_handles
        sleep(0.1)
        #print(list)
    print(list)
        

    #driver.switch_to.default_content()
    driver.switch_to.window(list[1])    # this selects new window OK
    sleep(2)
    #driver.maximize_window()
    curwin = driver.current_window_handle
    print('current window is ', curwin)
    print('waiting for google screen')
    #
    #sleep(2)

    driver.execute_script(cursor_script)  # adds dot at cursor position for testing
    
 
    #user_input(driver)
    #user_input(driver)
    #user_input(driver)
	
    nowwidth = driver.get_window_size().get("width")
    nowheight = driver.get_window_size().get("height")
    
    print('initial window size is ',nowwidth, nowheight)
    
    reqwidth = 1920
    reqheight = 1000

    driver.set_window_size(reqwidth, reqheight)
    #driver.maximize_window()
    print('window set for ', reqwidth, reqheight)
    sleep(1)

    nowwidth = driver.get_window_size().get("width")
    nowheight = driver.get_window_size().get("height")

    
    while nowheight != reqheight:
        print('awaiting window resize width')
        sleep(0.1)
        nowwidth = driver.get_window_size().get("width")
        nowheight = driver.get_window_size().get("height")
    
    while nowwidth != reqwidth:
        print('awaiting window resize height')
        sleep(0.1)
        nowwidth = driver.get_window_size().get("width")
        nowheight = driver.get_window_size().get("height")   
    
    print('window resized correctly')
    
    list = driver.window_handles
    print ('windows ' , list)
    #buttons = driver.find_elements(By.CSS_SELECTOR,"input[type='button']")
    elements = driver.find_elements(By.XPATH,'//*[@id]')   #  //*[@id]
    #buttons = driver.find_elements_by_xpath(".//form//input[@type='button']")
    print('elemments ',elements)

    #press for paused 
    test = []
    test = driver.find_elements(By.CSS_SELECTOR,"input[type='button']")
    if test != []:
        print('button found, trying to click')
        action = webdriver.common.action_chains.ActionChains(driver) 
        action.move_by_offset(970,550)  # this is from 0, 0 as new window
        #
        action.click()
        action.perform()
        sleep(0.1)
        
        action = webdriver.common.action_chains.ActionChains(driver) 
        action.move_by_offset(-970,-550)  # back to  0, 0 
        #
        #action.click()
        action.perform()
        sleep(0.1)  
    if test == []:
        print('no button found, trying alert')    
        try:
            driver.switch_to.alert
            print(alert.getText())
            alert.accept()
            driver.switch_to.window(curwin)
        except:
            print('no alert found')

    print('moving to search bar')
    ###   Move to  search bar and enter link to map            ###
    ###    Move to search bar              ###

    val = input("press any key to send url ")
    print(val)

    #clear any history warning
    action = webdriver.common.action_chains.ActionChains(driver) 
    action.move_by_offset(330,70)  # this is from 0, 0 as new window
    #
    action.click()
    action.perform()
    sleep(0.1)
    
    action = webdriver.common.action_chains.ActionChains(driver)
    action.move_by_offset(-1,0);
    action.click()
    action.perform()
    #
    sleep(0.1)

    ###    delete current entry             ###
    action = webdriver.common.action_chains.ActionChains(driver)
    action.send_keys(Keys.BACKSPACE)
    action.perform()
    print('search bar cleared')
    #
    sleep(0.1)

    ###    add link to map      ###
    action = webdriver.common.action_chains.ActionChains(driver)
    action.send_keys("https://nodered.securemapview.com/ui")
    action.perform()
    print('link added')
    #
    sleep(1)
    ###    then click to activate link      ###
    
    val = input("press any key to continue ")
    print(val)
    
    action = webdriver.common.action_chains.ActionChains(driver)
    action.move_by_offset(1,0);
    action.perform()
    print('link activated')
    sleep(0.1)

    action = webdriver.common.action_chains.ActionChains(driver)
    action.send_keys(Keys.ENTER)
    action.perform()
    #
    sleep(0.1)


    ###    move to "Advanced" button              ###
    action = webdriver.common.action_chains.ActionChains(driver) 
    action.move_by_offset(360,570)  # 
    action.click()
    action.perform()
    sleep(0.1)

    ###    move to "Proceed" button              ###
    action = webdriver.common.action_chains.ActionChains(driver) 
    action.move_by_offset(0,160)  # 
    action.click()
    action.perform()
    sleep(0.1)
    #then continually capture image
    #

    driver.switch_to.default_content() ###     move back up             ###



def screenshot(driver, count):  
    while (True):
        count = count + 1
        if count > 9:
            print('accessed ultra OK, saving screenshot')
            count = 0
            try:
                driver.save_screenshot('ss.png')
            except:
                print('unable to save screenshot')
        sleep(0.5)


            
###  main loop ##
count = 0
access = threading.Thread(target=access_ultra, args=())

access.start()

#stream = threading.Thread(target=stream_ultra, args=())
#stream.start()

        
