/*
** 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"
	"time"

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

func jaJobnetSummaryReady(innerJobnetId uint64, queries ...common.ParameterizedQuery) []common.ParameterizedQuery {
	return jaSetStatusJobnetSummary(innerJobnetId, JA_JOBNET_STATUS_RUN, 1, 0, queries...)
}

func jaJobnetReady(data *common.JobnetRunData, dbconn database.DBConnection, queries ...common.ParameterizedQuery) ([]common.ParameterizedQuery, error) {
	valueNames := []string{
		JOBNET_ID,
		JOBNET_NAME,
		USER_NAME,
		MANAGEMENT_ID,
		JOBNET_BOOT_TIME,
		JOBNET_BOOT_TIME_TZ,
		JOBNET_SCHEDULED_TIME,
		JOBNET_SCHEDULED_TIME_TZ,
		CURRENT_TIME,
		CURRENT_TIME_TZ,
		TIMEZONE,
	}

	queries, err := jaSetValueJobnetBefore(valueNames, *data, dbconn, queries...)
	if err != nil {
		return []common.ParameterizedQuery{}, fmt.Errorf("%s", err.Error())
	}
	return jaSetStatusJobnet(data.InnerJobnetId, JA_JOBNET_STATUS_RUN, 1, 0, queries...), nil
}

func jaJobnetTimeout(jobnetRunData common.JobnetRunData, queries ...common.ParameterizedQuery) []common.ParameterizedQuery {
	if jobnetRunData.JobnetTimeout > 0 {
		timeoutUnix := time.Now().Add(time.Duration(jobnetRunData.JobnetTimeout) * time.Minute).Unix()
		timeoutQuery := fmt.Sprintf(
			"INSERT into %s(inner_jobnet_id,jobnet_id,execution_user_name,timeout,timeout_run_type) VALUES(?,?,?,?,?)",
			common.Ja2RunTimeOutTable,
		)
		return append(queries, common.GetPQ(timeoutQuery, jobnetRunData.InnerJobnetId, jobnetRunData.JobnetID, jobnetRunData.UserName, timeoutUnix, jobnetRunData.TimeoutRunType))
	}
	return queries
}
