# -*- coding: utf-8 -*-
"""
Code to make GIFS of specific regions of TROPOMI NO2 Tropospheric Column
V01--Working only for the Canary Island Region

Authors: 
Santiago Ramirez Agudelo  BSC
Andrés Yarce Botero  BSC 
"""
import os
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from webdriver_manager.chrome import ChromeDriverManager
from PIL import Image
import time
import imageio.v2 as imageio

# Function to generate URLs for a given date range
def generate_urls(start_date, end_date):
    base_url = "https://mpc-l2.tropomi.eu/map_v2.html?map.id=tropomi/"
    date_format = "%Y/%m/%d"
    urls = []
    current_date = start_date
    while current_date <= end_date:
        date_str = current_date.strftime(date_format)
        url = f"{base_url}{date_str}/nitrogendioxide_tropospheric_column"
        urls.append(url)
        current_date += timedelta(days=1)
    return urls
# Capture map images from URL
def capture_map_image(url, save_path):
    # Set up Selenium WebDriver
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--window-size=1920x1080')  # Set window size to ensure full map is visible
    service = Service('/home/ayarce/.wdm/drivers/chromedriver/linux64/127.0.6533.72/chromedriver-linux64/chromedriver')
    driver = webdriver.Chrome(service=service, options=options)
    try:
        # Load the webpage
        driver.get(url)
        # Wait for the opacity change to take effect
        driver.implicitly_wait(2)
        # Click on the map to ensure it has focus
        map_element = driver.find_element(By.ID, 'map')
        actions = ActionChains(driver)
        actions.move_to_element(map_element).click().perform()
        # Press UP and LEFT arrow keys with a delay of 0.5 seconds
        time.sleep(0.1)
        actions.send_keys(Keys.ARROW_UP).perform()
        time.sleep(0.1)
        actions.send_keys(Keys.ARROW_LEFT).perform()
        # Select the zoom-in control and click it 5 times with a delay
        zoom_in_element = driver.find_element(By.CLASS_NAME, 'leaflet-control-zoom-in')
        for _ in range(5):
            time.sleep(0.1)
            zoom_in_element.click()
        # Press DOWN arrow key 10 times with a delay of 0.1 seconds
        for _ in range(10):
            time.sleep(0.1)
            actions.send_keys(Keys.ARROW_DOWN).perform()
        # Change the opacity of the first leaflet-layer element
        script_opacity = """
        var element = document.getElementsByClassName('leaflet-layer')[1];
        element.style.opacity = '0.5';
        """
        driver.execute_script(script_opacity)
        # Capture the screenshot of the map
        driver.save_screenshot(save_path)
    finally:
        # Clean up
        driver.quit()
    # Function to create GIF from images
def create_gif(image_folder, gif_path):
    images = []
    for file_name in sorted(os.listdir(image_folder)):
        if file_name.endswith('.png'):
            file_path = os.path.join(image_folder, file_name)
            images.append(imageio.imread(file_path))
    imageio.mimsave(gif_path, images, duration=100, loop=0)  # Adjust the duration as needed
# Define date range and output directory
start_date = datetime(2023, 1, 1)
end_date = datetime(2024, 1, 3)
output_dir = "maps"
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Generate URLs
urls = generate_urls(start_date, end_date)
# Capture and save map images for each URL
for url in urls:
    date_str = url.split("/")[-2]
    save_path = os.path.join(output_dir, f"map_{date_str}.png")
    capture_map_image(url, save_path)
gif_path = os.path.join(output_dir, "map_sequence.gif")
create_gif(output_dir, gif_path)
print("Map images have been captured and saved.")




