/*
** 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"
	"jobarranger2/src/libs/golibs/builder"
	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
	"jobarranger2/src/libs/golibs/logger/logger"
	"os"
	"path/filepath"
	"strings"
	"time"
)

func HostLockWait(processData common.FlowProcessData, execProcessData common.IconExecutionProcessData) error {
	funcName := "HostLockWait"
	nextEventData := common.EventData{}
	var jsonFile *os.File
	var err error

	nextEventData.Event.UniqueKey = common.GetUniqueKey(processName)
	nextEventData.Event.Name = common.EventIconHostUnlock

	processData.InnerJobId = execProcessData.RunJobData.InnerJobID
	processData.IconType = execProcessData.RunJobData.IconType

	nextEventData.NextProcess.Data = processData

	hostname := execProcessData.RunJobData.Data["host_name"].(string)
	folderPath := filepath.Join(server.Options.TmpDir, common.FlowManagerFolder, common.FlowManagerSubFolders[1], hostname)
	// Ensure destination directory exists
	if err := os.MkdirAll(folderPath, common.FilePermission); err != nil {
		return fmt.Errorf("failed to create target directory %s, err: [%w]", folderPath, err)
	}

	timeFormat := time.Now().Format("20060102150405.000000000")
	timeStamp := strings.ReplaceAll(timeFormat, ".", "_")
	filename := fmt.Sprintf("%d_%s_%d_%s.json", processData.InnerJobnetId, processData.JobnetId, processData.InnerJobId, timeStamp)
	fullFilePath := filepath.Join(folderPath, filename)

	if jsonFile, err = os.Create(fullFilePath); err != nil {
		return fmt.Errorf("create %s file failed under %s. [%v] ", filename, folderPath, err)
	}
	logger.JaLog("JAFLOW300006", logger.Logging{}, funcName,
		fullFilePath, processData.InnerJobId, processData.InnerJobnetId)
	defer jsonFile.Close()

	folderPath = filepath.Join(server.Options.TmpDir, common.FlowManagerFolder, common.FlowManagerSubFolders[0])
	fullFilePath = filepath.Join(folderPath, filename)
	nextEventData.Transfer.Files = append(nextEventData.Transfer.Files, common.FileTransfer{Source: fullFilePath})

	if err = builder.WriteJSON(jsonFile, nextEventData); err != nil {
		return fmt.Errorf("write json:%v file failed. [%v] ", (*jsonFile).Name(), err)
	}
	logger.JaLog("JAFLOW400002", logger.Logging{}, funcName,
		fmt.Sprintf("inner_joob_id: %d, inner_jobnet_id: %d",
			processData.InnerJobId, processData.InnerJobnetId))
	return nil
}
