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

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

func JaScheduleGetCalendarId(dbcon database.DBConnection, scheduleId string, calendarId *string) error {
	log.Printf("In %s() schedule_id: %s", "JaScheduleGetCalendarId", scheduleId)

	// 1. Get update_date from ja_2_schedule_control_table
	query := fmt.Sprintf(
		"SELECT update_date FROM ja_2_schedule_control_table WHERE schedule_id = '%s' AND valid_flag = 1",
		scheduleId,
	)
	fmt.Println(query)
	result, err := dbcon.Select(query)
	if err != nil {
		return fmt.Errorf(sqlErrFmt, "ja_2_schedule_control_table", query, err)
	}
	if !result.HasNextRow() {
		result.Free()
		return fmt.Errorf("[ERROR] : no rows found in ja_2_schedule_control_table for schedule_id %s", scheduleId)
	}
	row, err := result.Fetch()
	if err != nil {
		result.Free()
		return fmt.Errorf(fetchErrFmt, "ja_2_schedule_control_table", err)
	}
	updateDate := fmt.Sprintf("%v", row["update_date"])
	result.Free()

	// 2. Get calendar_id from ja_2_schedule_detail_table
	query = fmt.Sprintf(
		"SELECT calendar_id FROM ja_2_schedule_detail_table WHERE schedule_id = '%s' AND update_date = '%s'",
		scheduleId, updateDate,
	)
	result, err = dbcon.Select(query)
	if err != nil {
		return fmt.Errorf(sqlErrFmt, "ja_2_schedule_detail_table", query, err)
	}
	if !result.HasNextRow() {
		result.Free()
		return fmt.Errorf("[ERROR] : no rows found in ja_2_schedule_detail_table for schedule_id %s and update_date %s", scheduleId, updateDate)
	}
	row, err = result.Fetch()
	if err != nil {
		result.Free()
		return fmt.Errorf(fetchErrFmt, "ja_2_schedule_detail_table", err)
	}
	*calendarId = fmt.Sprintf("%v", row["calendar_id"])
	result.Free()

	return nil
}

func JaJobnetGetUserName(dbcon database.DBConnection, jobnetId string, userName *string) error {
	log.Printf("In %s() jobnet_id: %s", "JaJobnetGetUserName", jobnetId)

	// 1. Get user_name from ja_2_jobnet_control_table
	query := fmt.Sprintf(
		"SELECT user_name FROM ja_2_jobnet_control_table WHERE jobnet_id = '%s' AND valid_flag = 1",
		jobnetId,
	)
	result, err := dbcon.Select(query)
	if err != nil {
		return fmt.Errorf(sqlErrFmt, "ja_2_jobnet_control_table", query, err)
	}
	if !result.HasNextRow() {
		result.Free()
		return fmt.Errorf("[ERROR] : no rows found in ja_2_jobnet_control_table for jobnet_id %s", jobnetId)
	}
	row, err := result.Fetch()
	if err != nil {
		result.Free()
		return fmt.Errorf(fetchErrFmt, "ja_2_jobnet_control_table", err)
	}
	*userName = fmt.Sprintf("%v", row["user_name"])
	result.Free()

	return nil
}

func JaSender(dbcon database.DBConnection, id JA_SENDER_ID, scheduleId string, jobnetId string, scheduleTime string, startTime string) error {

	var calendarId string
	err := JaScheduleGetCalendarId(dbcon, scheduleId, &calendarId)
	if err != nil {
		return fmt.Errorf("[ERROR] %s", err.Error())
	}

	var username string
	err = JaJobnetGetUserName(dbcon, jobnetId, &username)
	if err != nil {
		return fmt.Errorf("[ERROR] %s", err.Error())
	}

	// Convert scheduleTime (string) to int64
	scheduleTimeInt, err := strconv.ParseInt(scheduleTime, 10, 64)
	if err != nil {
		return fmt.Errorf("[ERROR] %s", err.Error())
	}

	schTime := time.Unix(scheduleTimeInt, 0).Format("2006/01/02 15:04")

	var msg string
	switch id {
	case JA_SENDER_LOADER:
		msg = fmt.Sprintf("[ERROR] [JAMONITOR20000%d] Jobnet has not been pre-deployment: jobnet[%s]  scheduled time[%s]  calendar[%s]  schedule[%s]  user name[%s]",
			JA_SENDER_LOADER, jobnetId, schTime, calendarId, scheduleId, username)
	case JA_SENDER_RUN:
		msg = fmt.Sprintf("[ERROR] [JAMONITOR20000%d] Jobnet has not started: jobnet[%s]  scheduled time[%s]  calendar[%s]  schedule[%s]  user name[%s]",
			JA_SENDER_RUN, jobnetId, schTime, calendarId, scheduleId, username)
	default:
		break
	}

	msgMutex.Lock()
	messages = append(messages, msg)
	msgMutex.Unlock()

	return nil
}
