piotr-ginal / Click Input at Specific Time

// ==UserScript==
// @name         Click Input at Specific Time
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Clicks a submit button at the specified hour and minute
// @author       Piotr GinaƂ
// @license      MIT
// @match        *://*/*
// @grant        none
// ==/UserScript==

'use strict';

let query_selector = 'input[value="Rejestruj"]';

(function () {
    const input_element = document.querySelector(query_selector);

    if (!input_element) {
        return;
    }

    const target_hour = prompt("Enter the hour to click the register button:");

    const time_pattern = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/;

    if (time_pattern.test(target_hour)) {
        console.log("Valid time format");
    } else {
        console.error("Invalid time format");
        alert("Invalid hour entered! Please enter a value in 24h format, ex 13:31");
        return;
    }

    function click_button_at(time_string) {

        const [hours, minutes] = time_string.split(':').map(Number);
        const now = new Date();
        const target_time = new Date();

        target_time.setHours(hours, minutes, 0, 0);

        let delay = target_time - now;

        if (delay < 0) {
            delay += 24 * 60 * 60 * 1000;
        }

        delay += 20;

        console.log("Button will be clicked at:", time_string);

        setTimeout(() => {
            const nowCheck = new Date();
            if (nowCheck.getHours() === hours && nowCheck.getMinutes() === minutes && nowCheck.getSeconds() === 0) {
                const button = document.querySelector(query_selector);

                if (button) {
                    button.click();
                    console.log('Button clicked');
                }
                else {
                    console.error('Button not found');
                }
            }
        },
            delay
        );
    }

    click_button_at(target_hour);

})();