/*
** 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 events

import (
	"encoding/json"
	"fmt"
	"os"
	"path/filepath"
	"strconv"
	"strings"

	"jobarranger2/src/libs/golibs/common"
	"jobarranger2/src/libs/golibs/config_reader/server"
	"jobarranger2/src/libs/golibs/forker"
	"jobarranger2/src/libs/golibs/logger/logger"
)

func getLogging(processData common.IconExecutionProcessData) (*logger.Logging, error) {
	log := &logger.Logging{}

	log.InnerJobnetMainID = processData.RunJobData.InnerJobnetMainID
	log.InnerJobnetID = processData.RunJobData.InnerJobnetID
	log.InnerJobID = processData.RunJobData.InnerJobID
	log.JobType = processData.RunJobData.IconType
	log.JobStatus = processData.RunJobData.Status
	log.JobID = processData.RunJobData.JobID
	log.JobName = processData.RunJobData.JobName
	log.UpdateDate = processData.RunJobnetData.UpdateDate
	log.PublicFlag = processData.RunJobnetData.PublicFlag
	log.JobnetID = processData.RunJobnetData.JobnetID
	log.JobnetStatus = processData.RunJobnetData.Status
	log.JobnetName = processData.RunJobnetData.JobnetName
	log.RunType = processData.RunJobnetData.RunType
	log.MethodFlag = processData.RunJobData.MethodFlag
	log.JobName = processData.RunJobData.JobName
	log.UserName = processData.RunJobnetData.UserName

	if processData.RunJobData.IconType == common.IconTypeLess {
		var iconData common.IconLessData

		iconDataByte, err := json.Marshal(processData.RunJobData.Data)
		if err != nil {
			return nil, fmt.Errorf("json.Marshal(processData.RunJobData.Data) failed. error: %s", err.Error())
		}

		err = json.Unmarshal(iconDataByte, &iconData)
		if err != nil {
			return nil, fmt.Errorf("json.Unmarshal common.IconJobData failed. error: %s", err.Error())
		}

		log.SessionFlag = iconData.SessionFlag
	}

	return log, nil
}

func EventIconReady(eventData common.EventData) error {
	loadCommonVars()

	processData, ok := eventData.NextProcess.Data.(common.IconExecutionProcessData)
	if !ok {
		err := fmt.Errorf("expected data type: common.IconExecutionProcessData), data: %v", eventData.NextProcess.Data)
		log.JaLog("JAEXEC100001", eventData.Event.Name, err.Error(), eventData.NextProcess.Data)
		os.Exit(1)
	}

	log, err := getLogging(processData)
	if err != nil {
		errMsg, _ := log.JaLog("JAEXECRDY200003", log.InnerJobnetID, log.InnerJobID,
			log.JobnetID, log.JobID, err.Error())

		return setExecFail(errMsg, processData)
	}

	if processData.RunJobData.MethodFlag == common.MethodNormal {
		log.JaJobLog(common.JC_JOB_START)
	}

	log.JaLog("JAEXECRDY400001", log.InnerJobnetID, log.InnerJobID,
		log.JobnetID, log.JobID)

	if len(eventData.Transfer.Files) <= 0 {
		errMsg, _ := log.JaLog("JAEXECRDY200001", log.InnerJobnetID, log.InnerJobID,
			log.JobnetID, log.JobID)
		return setExecFail(errMsg, processData)
	}

	eventFile := filepath.Base(eventData.Transfer.Files[0].Source)
	transactionFileId := strings.TrimSuffix(eventFile, filepath.Ext(eventFile)) // removed .json extension

	forker := forker.New(forker.ProcessData{
		ExecPath: common.ClientHelperExecPath,
		ExecParams: []string{
			"-id", transactionFileId,
			"-uds", execManagerUdsPath,
			"-in", execManagerInPath,
			"-run", execManagerRunPath,
			"-end", execManagerEndPath,
			"-error", execManagerErrorPath,
			"-clientdata", clientDataPath,
			"-ret", filepath.Join(clientDataPath, transactionFileId+common.ClientReturnExt),
			"-udsdir", server.Options.UnixSockParentDir,
			"-tmpdir", server.Options.TmpDir,
			"-timeout", strconv.Itoa(server.Options.Timeout),
			"-sourceIp", server.Options.SourceIP,
		},
		Detached:   true,
		StdoutPath: filepath.Join(clientDataPath, transactionFileId+common.ClientStdoutExt),
		StderrPath: filepath.Join(clientDataPath, transactionFileId+common.ClientStderrExt),
	})

	_, err = forker.StartNewProcess()
	if err != nil {
		errMsg, _ := log.JaLog("JAEXECRDY200002", log.InnerJobnetID, log.InnerJobID,
			log.JobnetID, log.JobID, err.Error())
		return setExecFail(errMsg, processData)
	}

	log.JaLog("JAEXECRDY400002", log.InnerJobnetID, log.InnerJobID,
		log.JobnetID, log.JobID)

	return nil
}
