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

import (
	"encoding/json"
)

type FlowProcessData struct {
	InnerJobnetId uint64     `json:"inner_jobnet_id"`
	JobnetId      string     `json:"jobnet_id"`
	InnerJobId    uint64     `json:"inner_job_id"`
	IconType      IconType   `json:"icon_type"`
	FlowType      FlowType   `json:"flow_type"`
	Status        StatusType `json:"status"`
	ExitCode      int        `json:"exit_code"`

	Data interface{} `json:"data"`
	//additional data eg:JobResultData/CheckJobData/IconExecutionProcessData
}

type IconExecutionProcessData struct {
	RunJobData         RunJobTable           `json:"run_job_data"`
	RunJobnetData      RunJobnetTable        `json:"run_jobnet_data"`
	RunJobVariableData RunJobVariableTable   `json:"run_job_variable_data"`
	RunValueJobConData []RunValueJobConTable `json:"run_value_jobcon_data"` // only for job icon
	RunValueJobData    []RunValueJobTable    `json:"run_value_job_data"`    // only from job icon
	SessionData        SessionTable          `json:"session_data"`          // only for agentless icon
	JobResult          JobResultData         `json:"job_result"`
	ParameterData      ParameterTable        `json:"parameter_data"`     // only for extended icon
	JobnetStartTime    int64                 `json:"jobnet_start_time"`  // only for extension icon
	JobnetRunData      JobnetRunData         `json:"jobnet_run_data"`    // only for jobnet icon
	CheckProcessData   CheckProcess          `json:"check_process_data"` // check_process for job,fwait,reboot(Agent)
	RunTimeoutData     RunTimeoutTable       `json:"run_timeout_data"`   // extension icon's check_process
}

type IconRunData struct {
	TransactionFileId string                   `json:"transaction_file_id"`
	Result            JobResult                `json:"result"`
	ExecProcessData   IconExecutionProcessData `json:"exec_process_data"`
	ClientData        map[string][]byte        `json:"client_data"`
}

type IconTimeoutData struct {
	TimeoutRunType int    `json:"timeout_run_type"`
	Timeout        uint64 `json:"timeout"`
}

// Stw
type JobnetRunData struct {
	RunType                  int             `json:"run_type"`
	ScheduledTime            uint64          `json:"scheduled_time"`
	MultipleOptions          int             `json:"multiple_start_up"`
	MainFlag                 JaMainFlag      `json:"main_flag"`
	Status                   StatusType      `json:"status"`
	JobnetID                 string          `json:"jobnet_id"`
	JobnetName               string          `json:"jobnet_name"`
	UserName                 string          `json:"user_name"`
	InnerJobnetMainId        uint64          `json:"inner_jobnet_main_id"`
	InnerJobnetId            uint64          `json:"inner_jobnet_id"`
	InnerJobId               uint64          `json:"inner_job_id"`
	JobType                  int             `json:"job_type"`
	StartPendingFlag         int             `json:"start_pending_flag"`
	TimeoutRunType           int             `json:"timeout_run_type"`
	IconTimeoutRunType       int             `json:"icon_timeout_run_type"`
	LoadStatus               int             `json:"load_status"`
	JobnetTimeout            int64           `json:"jobnet_timeout"`
	Message                  string          `json:"message"`
	Timezone                 string          `json:"timezone"`
	UpdateDate               uint64          `json:"update_date"`
	PublicFlag               int             `json:"public_flag"`
	JobId                    string          `json:"job_id"`
	TestRunTime              uint64          `json:"test_run_time"`
	CreatedDate              uint64          `json:"created_date"`
	JobnetIconBeforeVariable json.RawMessage `json:"jobnet_iconbefore_variable"`
	ActionIconData           ActionIconData  `json:"action_icon_data"`
	IconStopInterval         uint64          `json:"icon_stop_interval"`
}

type JobnetStatusChange struct {
	InnerJobnetId uint64     `json:"inner_jobnet_id"`
	JobnetId      string     `json:"jobnet_id"`
	Status        StatusType `json:"status"`
}

type HostResult struct {
	Hostname string
	IP       string
	Port     int
	Status   int
	Dns      string
	Error    string
}

type CheckProcess struct {
	HostResult      HostResult `json:"host_result"`
	ServerID        string     `json:"server_id"`
	Jaz1SupportFlag int        `json:"jaz1_support_flag"`
	JobIdList       []uint64   `json:"job_id_list"` // reboot, fwait, job
}

type HostArgs struct {
	Hostname  string
	Macroname string
}

type HostData struct {
	Hosts []HostArgs
}

type IconStartData struct {
}

type IconEndData struct {
	JobnetStopCode string `json:"jobnet_stop_code"`
	JobnetStopFlag int    `json:"jobnet_stop_flag"`
}

type IconIfData struct {
	HandFlag        int      `json:"hand_flag"`
	ValueName       string   `json:"value_name"`
	ComparisonValue string   `json:"comparison_value"`
	FlowType        FlowType `json:"flow_type"`
}

type IconValueDataWrap struct {
	Variables []IconValueData `json:"variables"`
}

// IconValueData represents a single variable icon with a name and value.
// This structure corresponds to each object in the "variables" array of the JSON payload
type IconValueData struct {
	Variables map[string]string `json:"variables"`
}

type IconJobData struct {
	ServerID        string  `json:"serverid"`
	HostFlag        int     `json:"host_flag"` // integer NOT NULL
	HostPort        int     `json:"host_port"`
	StopFlag        int     `json:"stop_flag"`    // integer NOT NULL
	CommandType     int     `json:"command_type"` // integer NOT NULL
	Timeout         int     `json:"timeout"`      // integer NOT NULL
	Jaz1SupportFlag int     `json:"jaz1_support_flag"`
	HostIp          string  `json:"host_ip"`
	HostName        string  `json:"host_name"`        // varchar(128) NOT NULL
	StopCode        *string `json:"stop_code"`        // varchar(32) NULL
	TimeoutRunType  int     `json:"timeout_run_type"` // integer NOT NULL
	Command         string  `json:"command"`
	StopCommand     string  `json:"stop_command,omitempty"` // NULL
}

type IconExtData struct {
	CommandId string `json:"command_id"`
	Value     string `json:"value"`
	Pid       int    `json:"pid"`

	WaitTime    int64 `json:"wait_time"`
	JobExitCode int   `json:"job_exit_code"`
	TimeOut     int   `json:"time_out"`
}

type IconJobnetData struct {
	LinkJobnetId      string `json:"link_jobnet_id"`
	LinkInnerJobnetID uint64 `json:"link_inner_jobnet_id"`
}

type IconMData struct {
}

type IconWData struct {
	EndCountPlusFlag bool `json:"end_count_plus_flag"`
}

type IconCalcData struct {
	HandFlag  int    `json:"hand_flag"`
	Formula   string `json:"formula"`
	ValueName string `json:"value_name"`
	Value     string `json:"value"` // using this only for data passing from exec_manager to result_manager
}

type IconTaskData struct {
	SubmitInnerJobnetId uint64 `json:"submit_inner_jobnet_id"`
	SubmitJobnetId      string `json:"submit_jobnet_id"`
}

type IconInfoData struct {
	InfoFlag      int    `json:"info_flag"`
	ItemId        int    `json:"item_id"`
	TriggerId     int    `json:"trigger_id"`
	HostGroup     string `json:"host_group"`
	HostName      string `json:"host_name"`
	GetJobId      string `json:"get_job_id"`
	GetCalendarId string `json:"get_calendar_id"`
	Status        int    `json:"status"`
}

type IconIfEndData struct {
	EndCountPlusFlag bool `json:"end_count_plus_flag"`
}

type IconFCopyData struct {
	ServerID        string `json:"serverid"`
	FromHostFlag    int    `json:"from_host_flag"`
	FromHostPort    int    `json:"from_host_port"`
	ToHostFlag      int    `json:"to_host_flag"`
	ToHostPort      int    `json:"to_host_port"`
	OverwriteFlag   int    `json:"overwrite_flag"`
	FcopyTimeout    int    `json:"fcopy_timeout"`
	Jaz1SupportFlag int    `json:"jaz1_support_flag"`
	FromHostName    string `json:"from_host_name"`
	FromHostIp      string `json:"from_host_ip"`
	FromDirectory   string `json:"from_directory"`
	FromFileName    string `json:"from_file_name"`
	ToHostName      string `json:"to_host_name"`
	ToHostIp        string `json:"to_host_ip"`
	ToDirectory     string `json:"to_directory"`
	IsJaz1          bool   `json:"is_jaz1"`
}

type IconFWaitData struct {
	ServerID        string `json:"serverid"`
	HostFlag        int    `json:"host_flag"`
	HostIp          string `json:"host_ip"`
	HostPort        int    `json:"host_port"`
	FwaitModeFlag   int    `json:"fwait_mode_flag"`
	FileDeleteFlag  int    `json:"file_delete_flag"`
	FileWaitTime    int    `json:"file_wait_time"`
	Jaz1SupportFlag int    `json:"jaz1_support_flag"`
	HostName        string `json:"host_name"`
	FileName        string `json:"file_name"`
}

type IconRebootData struct {
	ServerID        string `json:"serverid"`
	HostFlag        int    `json:"host_flag"`
	HostIp          string `json:"host_ip"`
	HostPort        int    `json:"host_port"`
	RebootModeFlag  int    `json:"reboot_mode_flag"`
	RebootWaitTime  int    `json:"reboot_wait_time"`
	Jaz1SupportFlag int    `json:"jaz1_support_flag"`
	HostName        string `json:"host_name"`
	TimeOut         int    `json:"timeout"`
}

type IconRelData struct {
	ReleaseJobId      string `json:"release_job_id"`
	ReleaseInnerJobId uint64 `json:"release_inner_job_id"`
}

type IconLessData struct {
	Command          string `json:"command"`
	Timeout          int    `json:"timeout"`
	RunMode          int    `json:"run_mode"`
	HostFlag         int    `json:"host_flag"`
	HostName         string `json:"host_name"`
	HostIp           string `json:"host_ip"`
	HostPort         int    `json:"host_port"`
	StopCode         string `json:"stop_code"`
	LoginUser        string `json:"login_user"`
	Passphrase       string `json:"passphrase"`
	PublicKey        string `json:"public_key"`
	SessionID        string `json:"session_id"`
	AuthMethod       int    `json:"auth_method"`
	PrivateKey       string `json:"private_key"`
	SessionFlag      int    `json:"session_flag"`
	PromptString     string `json:"prompt_string"`
	TerminalType     string `json:"terminal_type"`
	CharacterCode    string `json:"character_code"`
	LineFeedCode     int    `json:"line_feed_code"`
	LoginPassword    string `json:"login_password"`
	ConnectionMethod int    `json:"connection_method"`
	SshClientUdsPath string `json:"ssh_client_uds_path"`
	SshClientPid     int    `json:"ssh_client_pid"`
	JobExitCode      int    `json:"job_exit_code"`
}

type IconLinkData struct {
	TestFlag      int    `json:"test_flag"`
	LinkTarget    int    `json:"link_target"`
	LinkOperation int    `json:"link_operation"`
	GroupId       string `json:"groupid"`
	HostId        string `json:"hostid"`
	ItemId        string `json:"itemid"`
	TriggerId     string `json:"triggerid"`
	ZBXLastStatus int    `json:"zbx_last_status"`
	ZBXLatestData string `json:"zbx_lastest_data"`
	ZBXDataType   int    `json:"zbx_data_type"`
	ExecUserName  string `json:"execution_user_name"`
	InnerJobId    uint64 `json:"inner_job_id"`
}

type SessionData struct {
	SSHClientSocket string `json:"ssh_client_socket"`
}

type ZabbixIconResult struct {
	Output IconLinkData
	Error  string
}

// Agent manager structs
type TCPMessage struct {
	SendRetry      *int    `json:"sendretry,omitempty"`
	Kind           string  `json:"kind"`
	Version        float64 `json:"version"`
	ServerID       string  `json:"serverid"`
	Hostname       string  `json:"hostname"`
	JazVersion     *int    `json:"jaz_version,omitempty"`
	EncryptVersion float64 `json:"encrypt_version"`
	Data           any     `json:"data"`
}

type ResponseData struct {
	Result      int     `json:"result"`
	Message     *string `json:"message,omitempty"`
	PreUniqueID *string `json:"pre_unique_id,omitempty"`
}

type JobRunRequestData struct {
	JobID           string            `json:"jobid"`
	Type            AgentJobType      `json:"type"`
	Method          AgentMethod       `json:"method"`
	Script          string            `json:"script"`
	CurUniqueID     string            `json:"cur_unique_id"`
	PreUniqueID     string            `json:"pre_unique_id"`
	Argument        any               `json:"argument"`
	Env             map[string]string `json:"env"`
	RunUser         *string           `json:"run_user"`
	RunUserPassword *string           `json:"run_user_password"`
}

type JobResultData struct {
	JobRunRequestData
	JobStatus       AgentJobStatus `json:"jobstatus"`
	PID             int            `json:"pid"`
	Message         string         `json:"message"`
	Hostname        string         `json:"hostname"`
	Result          int            `json:"result"`
	StdOut          string         `json:"std_out"`
	StdErr          string         `json:"std_err"`
	ReturnCode      any            `json:"return_code"`
	Signal          int            `json:"signal"`
	HostJobList     []uint64       `json:"host_job_list"`
	JazVersion      int            `json:"jaz_version,omitempty"`
	CheckJobFlag    bool           `json:"check_job_flag"`
	PreExecFailFlag bool           `json:"pre_exec_fail_flag"`
}

type RebootArgument struct {
	RebootModeFlag int `json:"reboot_mode_flag"`
	RebootWaitTime int `json:"reboot_wait_time"`
}

type FcopyArgumentData struct {
	FromDir   string `json:"fromdir"`
	Filename  string `json:"filename"`
	ToDir     string `json:"todir"`
	Overwrite int    `json:"overwrite"`
}

type ZbxSendInfo struct {
	InnerJobID    uint64 `json:"inner_job_id"`
	InnerJobnetID uint64 `json:"inner_jobnet_id"`
	LogMessage    string `json:"log_message"`
	LogMessageID  string `json:"log_message_id"`
	LogLevel      int    `json:"log_level"`
}

type CheckJobData struct {
	HostName       string   `json:"host_name"`
	CheckJobIdList []uint64 `json:"check_job_id_list"`
}

type AgentDataW struct {
	EventData      []byte
	SocketFilePath string
	ServerIp       string
}

type EventFileNameParts struct {
	InnerJobnetID uint64
	JobnetID      string
	InnerJobID    uint64
	Timestamp     string
	Extension     string
	FilePath      string
	ManagerName   string
}

type ActionIconData struct {
	InnerJobnetID uint64
	JobnetID      string
	InnerJobID    uint64
	MethodFlag    JobRunMethod
}
