#Copyright © 2025 – WildGate Consultancy Solutions Limited – all Rights Reserved
#Proof of concept to constantly capture image from mapserver
#
#  *****************************************************************************************
#  *****************************************************************************************
#    To capture QR code that is streamed from      :8501 and save data to file so that maps can access data
#
#  ************************************************************************************************
#    ********************************************************************************************
#
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 json
from cv2 import *
from pyzbar.pyzbar import decode
from pyzbar.pyzbar import ZBarSymbol


prevLoc=[1,1]
Log = 'On'
global QRCount
QRCount = 0

#def access_QRCode():
 
print ("starting ...")
options = Options()
#options.headless = True  # remed out 25/1/24
#options.add_argument("window-size=200,200") # 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

print ("starting  driver..")
driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)  # added 20/8/25

url = "http://167.172.48.157:8502/"


def GetLocation():
     #Location = decode(Image.open("Loc.jpg"), symbols=[ZBarSymbol.QRCODE])
     tempimg= cv2.imread("ss.png")
     tempimg2 = tempimg[80:480, 80:480]   #  [ x:x+w, y:y + h]
     cv2.imwrite('ss2.png', tempimg2)
     Location = decode(tempimg2, symbols=[ZBarSymbol.QRCODE])
     #Location = decode(cv2.imread("ss.png"), symbols=[ZBarSymbol.QRCODE])
     #print(Location)
     global prevLoc
     global QRCount
     if  ( Location!=prevLoc and Location!=[]):

         prevLoc=Location
         Result=str(Location[0].data)
         Rlength= len(Result)
         subResult = Result[2:(Rlength-1)]
         Data=subResult.split(",")
         
         length =len(Data)

         if length == 4:
             valid=1
             if -180 >= float(Data[0]) <= 180:
                  valid=0
                  print("West not in range")
             if -180 >= float(Data[2]) <= 180:
                  valid=0
                  print("East not in range")
             if -90 >= float(Data[1]) <= 90:
                  valid=0
                  print("South not in range")
             if -90 >= float(Data[3]) <= 90:
                  valid=0
                  print("North not in range")
             if valid==1:   
                  west=(Data[0])      
                  south=(Data[1])
                  east=(Data[2]) 
                  north=(Data[3])
                  data = []  
                  data.append({
                      'W': west,
                      'S': south,
                      'E': east,
                      'N': north,
                      })
                  LocToSave = 'Location.json'
                  with open(LocToSave, 'w') as outfile:
                      json.dump(data, outfile)
                  if Log == "On":
                      print("Change detected")
                      print(Data)            
                      #print("json output")
             if valid == 0:
                 print (" Lat , Long values error")
                 print(Data)   

         else:
            print ("Error, incorrect data read")
     if  ( Location==[]):
        QRCount = QRCount + 1
        if (QRCount >= 20):
            print ("No QR Code in last 20 loops")
            QRCount = 0
        #print ("No QR Code")
   ############ end of GetLocation
    


print ("starting .url.test.")
driver.get(url)
sleep(3)
print ("got to  .url..")

winsize = driver.get_window_rect()
print(winsize)

nowwidth = driver.get_window_size().get("width")
nowheight = driver.get_window_size().get("height")
while True:
    try:
        #print ("starting ..scrn.")
        driver.save_screenshot('ss.png')  # this works
    except:
        print('unable to save screenshot')
    GetLocation()       
    sleep(1)   
        


        
