/*
** Job Arranger for ZABBIX
** Copyright (C) 2025 Daiwa Institute of Research Ltd. All Rights Reserved.
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
**/
package main

import (
	"fmt"
	"os"
	"strconv"
	"time"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/database"
)

func JaCheckRun(dbcon database.DBConnection, RunShiftTime int) error {
	fmt.Printf("%d:%s [DEBUG] In JaCheckRun().\n", os.Getppid(), time.Now().Format("20060102:150405.000"))
	now := time.Now().Unix() // current Unix time (seconds since epoch)

	offsetSeconds := (1 + RunShiftTime) * 60
	t := now - int64(offsetSeconds)
	query := fmt.Sprintf(
		"SELECT start_time, scheduled_time, jobnet_id, schedule_id FROM ja_2_run_jobnet_summary_table WHERE run_type = %d AND start_pending_flag = %d",
		common.JA_JOBNET_RUN_TYPE_NORMAL, JA_SUMMARY_START_PENDING_NONE,
	)

	result, err := dbcon.Select(query)
	if err != nil {
		return fmt.Errorf(sqlErrFmt, "ja_2_run_jobnet_summary_table", query, err)
	}

	for result.HasNextRow() {
		row, err := result.Fetch()
		if err != nil {
			return fmt.Errorf(fetchErrFmt, "ja_2_run_jobnet_summary_table", err)
		}

		startTime := fmt.Sprintf("%v", row["start_time"])
		scheduleTimeStr := fmt.Sprintf("%v", row["scheduled_time"])
		jobnetId := fmt.Sprintf("%v", row["jobnet_id"])
		scheduleId := fmt.Sprintf("%v", row["schedule_id"])

		scheduleTimeInt, err := strconv.Atoi(scheduleTimeStr)
		if err != nil {
			return fmt.Errorf("[ERROR] : failed to convert scheduled_time to int: %w", err)
		}
		fmt.Printf("schedule_id=%s, jobnet_id=%s, scheduleTime=%s, start_time=%s\n", scheduleId, jobnetId, scheduleTimeStr, startTime)
		if t >= int64(scheduleTimeInt) && t < int64(scheduleTimeInt)+60 {
			if startTime == "0" {
				err := JaSender(dbcon, JA_SENDER_RUN, scheduleId, jobnetId, scheduleTimeStr, startTime)
				if err != nil {
					return fmt.Errorf("[ERROR] : failed to send run jobnet: %w", err)
				}
			}
		}
	}
	return nil
}
