 SET NAMES utf8;
DELIMITER $$

/* ************************************************************************************************************************************************************************
	
************************************************************************************************************************************************************************ */	

DROP FUNCTION IF EXISTS `_sys_cmd_ff`$$
CREATE DEFINER=`root`@`localhost` FUNCTION `_sys_cmd_ff`(
	_MODE VARCHAR(200),
	_ID VARCHAR(255),			--	tylko dla GET
	_cmd TEXT,				--	Cmd
	_Param_A VARCHAR(255),	--	
	_Param_B VARCHAR(255),	--	
	_Params VARCHAR(1024)
	) 
RETURNS VARCHAR(250)
    NO SQL
    DETERMINISTIC
    COMMENT 'obsługa tabeli _sys_cmd'
BEGIN
	/* ************************************************************************************************************************************************************************
		K=|key=
		S=|start=
		U=|until=
		T=|Trials=
		C=|Cyclic=
		_sys_cmd_ff('ADD', '', '', '', '')
	************************************************************************************************************************************************************************ */	
	IF _MODE IN ('ADD', 'ADD.CYCLIC', 'ADD.Never') THEN
		SET 
			@.NEW.ID = NULL,
			@_Params = _Params,
			@.NEW.kind = IF(_MODE LIKE 'ADD.CYCLIC', 'Cyclic', IF(_MODE LIKE 'ADD.Never', 'Never', 'ToDo'))
		;
		IF NULLIF(@_Params, '') IS NOT NULL THEN
			SET
				@.NEW.cmd_key = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'K', ''), 
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'KEY', '')),
				@.NEW.Start_AT = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'S', ''), 
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'START', '')),
				@.NEW.Until_AT = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'U', ''), 
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'UNTIL', '')),
				@.NEW.Trials = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'T', ''), 
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'Trials', '')),
				@.NEW.Cyclic_Sec = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'C', ''),
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'Cyclic', '')),
				@.NEW.Src_Session = IFNULL(
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'S.ID', ''),
					_Params2('_FetchParams_QuickNull', @_ModeParam, @_Params, 'Session', ''))
			;
		ELSE
			SET
				@.NEW.cmd_key = NULL,
				@.NEW.Start_AT = NULL,
				@.NEW.Until_AT = NULL,
				@.NEW.Trials = NULL,
				@.NEW.Cyclic_Sec = NULL,
				@.NEW.Src_Session = NULL
			;
		END IF;
		SET
			@.NEW.Start_AT = 
				IF(@.NEW.Start_AT IS NULL,
					NOW() + INTERVAL 0 SECOND,
					IF(@.NEW.Start_AT LIKE '+%',
						NOW() + INTERVAL REPLACE(@.NEW.Start_AT, '+', '') MINUTE,
						@.NEW.Start_AT
					)
				)
		;
		IF @.NEW.kind = 'ToDo' THEN
			SET
				@.NEW.OK := TRUE,
				@.NEW.cmd_key = NULL,
				-- @.NEW.Until_AT = GREATEST(@.NEW.Start_AT + INTERVAL 10 MINUTE, IFNULL(NULLIF(@.NEW.Until_AT, ''), @.NEW.Start_AT)),
				@.NEW.Cyclic_Sec = 0,
				@.NEW.Trials = GREATEST(1, IFNULL(@.NEW.Trials, 1)),
				@.NEW.Until_AT = GREATEST(@.NEW.Start_AT + INTERVAL 10 MINUTE, IFNULL(@.NEW.Until_AT, NOW())),
				@.NEW.Src_Session = IFNULL(
						IF(@.NEW.Src_Session = '+', 
							@SYSTEM.Client.Session.GUID, 	-- + oznacza domyslną sesję!!!
							@.NEW.Src_Session
						),
						NULL
					)
			;
		END IF;
		IF @.NEW.kind = 'Cyclic' THEN
			SET
				@.NEW.cmd_key := NULLIF(IFNULL(@.NEW.cmd_key, _ID), ''),
				@.NEW.OK := @.NEW.cmd_key IS NOT NULL,
				@.NEW.Cyclic_Sec := GREATEST(30, IFNULL(@.NEW.Cyclic_Sec, 0)),
				@.NEW.Until_AT = GREATEST(NOW() + INTERVAL 10 MINUTE, IFNULL(@.NEW.Until_AT, '2100-01-01 00:00:00')),

				@.NEW.Trials = 1,
				@.NEW.Src_Session = NULL
			;
		END IF;
		IF @.NEW.kind = 'Never' THEN
			SET
				@.NEW.cmd_key := NULLIF(IFNULL(@.NEW.cmd_key, _ID), ''),
				@.NEW.OK := @.NEW.cmd_key IS NOT NULL,
				@.NEW.Cyclic_Sec = 0,
				@.NEW.Trials = NULL,
				@.NEW.Src_Session = NULL,
				@.NEW.Start_AT = NULL,
				@.NEW.Until_AT = NULL
			;	
		END IF;
	--	UWAGA nie zakładamy cyklicznych bez cmd_key ...
		IF @.NEW.OK THEN
		--	gdyby byl cykliczny to bez _cmd_key TUTAJ nie wchodzimy
												set @.wchodze = 1;
			INSERT INTO `_sys_cmd`
			SET
				kind = @.NEW.kind,
				cmd_key = @.NEW.cmd_key,
				cmd = _Cmd,
				cmd_size = LENGTH(_Cmd),
				cmd_status = 
					IF(@.NEW.kind = 'Never',
						'Never',
						IF(@.NEW.Start_AT > NOW() + INTERVAL 2 SECOND,
							'...Wait', 
							'...Standby'
						)
					),
				cmd_status_inf = 
					-- IF(@._sys_cmd.Start_AT > @._sys_cmd.Put_AT,
					IF(@.NEW.Start_AT > NOW() + INTERVAL 2 SECOND,
						'...Wait', 
						NULL
					),
				-- Put_At = NOW(),
				Cyclic_Sec = @.NEW.Cyclic_Sec,
				Src_Session = @.NEW.Src_Session, 
				Trials = @.NEW.Trials,
				Trials_Left = @.NEW.Trials,
				Start_AT = @.NEW.Start_AT,
				Until_AT = @.NEW.Until_AT,
				Release_After = NULL -- GREATEST(@._sys_cmd.Put_AT + INTERVAL 0 HOUR, IFNULL(_Release_After, '')),
			ON DUPLICATE KEY UPDATE
				kind = @.NEW.kind,
				cmd = _Cmd,
				cmd_size = LENGTH(_Cmd),
				cmd_status =
					IF(@.NEW.Start_AT > NOW() + INTERVAL 2 SECOND,
						'...Wait', 
						'...Standby'
					),
				cmd_status_inf = CONCAT_WS('->', 
					'RENEW'
				),
				Cyclic_Sec = @.NEW.Cyclic_Sec,
				Src_Session = @.NEW.Src_Session, 
				Trials = @.NEW.Trials,
				Trials_Left = @.NEW.Trials,
				Start_AT = @.NEW.Start_AT,
				Until_AT = @.NEW.Until_AT,
				-- Put_At = NOW(),
				Release_After = NULL
			;					
			SET @.NEW.ID = LAST_insert_ID();
		END IF;
		SET @._sys_cmd.RETURN = @.NEW.ID;


	END IF;

	IF _MODE = 'DELETE.OLD' OR @._sys_cmd.Do.DELETE THEN
	--	Najpierw Wait na Standby
		UPDATE `_sys_cmd` c
		SET
			c.cmd_status = '...Standby'
			-- c.cmd_status_inf = '...Standby'
		WHERE
			c.kind <> 'Never'
			AND c.cmd_status LIKE '...Wait'
			AND c.Start_AT < NOW() + INTERVAL 30 SECOND
		;
	--	Teraz usuwanie	
		SET @._sys_cmd.Do.DELETE = FALSE;
		UPDATE `_sys_cmd` c
		SET
			c.Release_After = 
				IF(c.kind = 'Cyclic',
					NOW() + INTERVAL 10 MINUTE,		-- TEST wstaw jakas a=zmiena systemowa !!!!!!!!!!!!!!!!!!!!!!!!!
					NOW() + INTERVAL 20 MINUTE			-- TEST wstaw jakas a=zmiena systemowa !!!!!!!!!!!!!!!!!!!!!!!!!
				),
			c.cmd_status = CONCAT_WS('.', 'Arch', REPLACE(c.cmd_status, 'Arch.', '')),
			c.cmd_status_inf = CONCAT_WS('->', 
				IFNULL(NULLIF(c.cmd_status_inf, ''), '...Standby'), 	-- c.cmd_status_inf, 
				'OVER.TIME',
				'ARCH'
			),
			-- c.Start_AT = NULL,
			c.cmd_key = CONCAT(c.ID, '.', c.cmd_key)
		WHERE
			c.kind <> 'Never'
			-- AND LEAST(c.Until_AT, c.Done_AT) < NOW()
			AND c.Release_After < NOW()
			-- AND c.cmd_status IN ('', '...Standby', '...Wait', 'Executing...', 'DONE', 'ERROR', 'FAIL')
			AND NOT(c.cmd_status LIKE 'Arch.%')
			
			-- AND c.Cyclic_Sec = 0
		;
		DELETE FROM `_sys_cmd` 
		WHERE 
			cmd_status LIKE 'Arch.%'
			AND Release_After < NOW() 
		;
		SET @._sys_cmd.COUNT = ROW_COUNT();
		SET @._sys_cmd.RETURN = @._sys_cmd.COUNT;
	END IF;

	IF _MODE IN ('Keep.1.for.Execute') THEN
	/************************************************************************************************
		DO _sys_cmd_ff('Keep.1.for.Execute', _ID, '', '', '', '');
		_ID			id rekordu
	************************************************************************************************/
		UPDATE `_sys_cmd` c
		SET
			c.Exe_Con = CONNECTION_ID(),
			c.Last_Exe_AT = NOW(),
			c.cmd_status = (@.c.cmd_status := 'Executing...'),

			c.cmd_status_inf = CONCAT_WS('->', 
				NULLIF(c.cmd_status_inf, ''), 	-- c.cmd_status_inf, 
				'EXE...'
			),
			c.Trials_Log = 
				CONCAT_WS('\n', 
					NULLIF((c.Trials_Log), ''),
					CONCAT(
						'', _VarStr(c.Trials - c.Trials_Left + 1), '. ', _VarStr(NOW()), ': ',
						IFNULL(NULLIF(c.cmd_status, ''), 'START') 
						-- ' -> ', 
						-- @.c.cmd_status
					)
				),
			c.Trials_Left = c.Trials_Left - 1
		WHERE
			c.ID = _ID
			AND c.kind <> 'Never'
			-- AND c.cmd_status IN ('', '...Standby', '...Wait')
			AND c.cmd_status LIKE '...%'
			AND c.Exe_Con IS NULL
			-- AND IFNULL(c.Exe_Con, 0) = 0 -- IS NULL
			AND c.Trials_Left > 0
			AND c.Start_AT <= NOW()
			AND c.Until_AT >= NOW()
		;			
		SET @._sys_cmd.COUNT = ROW_COUNT();
		SET @._sys_cmd.RETURN = (@._sys_cmd.COUNT > 0);	--	zwraca 1 gdy jest cos do wykonania -> @._sys_cmd.Let.Exe
	END IF;
	
	IF _MODE IN ('AFTER.EXE') THEN
	/************************************************************************************************
		DO _sys_cmd_ff('AFTER.EXE', _ID, '', '', '', '');
		_Start_AT 	@.System.EVENT.Run_Start brany z @@TimeStamp
		_Until_AT 	@.System.EVENT.Run_Stop brany z @@TimeStamp
		cmd_status:
			""
			"Standby"
			"Wait"		"Wait[(trial)]" np."Wait(2)"
			"Executing..."	/	"IN.PROGRESS"	/	"PROGRESS..."
			"Done"
			"Done.Fail"
			"Done.Error"
	************************************************************************************************/
		SET
			@.NEW.cmd_key = NULL,		--	WAŻNE bo od tego zalezy Insert cyklicznego!!!
			@.System.EVENT.CALL.IS.DONE = (IFNULL(@.System.EVENT.ERROR, 0) = 0 AND IFNULL(@.System.EVENT.CALL.State, '') = '')
		;
		UPDATE `_sys_cmd` c
		SET
			c.cmd_key = 
				IF(c.Kind = 'Cyclic',
					CONCAT((@.NEW.cmd_key := c.cmd_key), '.', c.ID),	-- tylko dla cyklicznego!!!
					c.cmd_key
				),
			c.cmd_status = (@.c.cmd_status :=
				IF(@.System.EVENT.CALL.IS.DONE, 
					'Done', 
					CONCAT_WS('.',
						IF(c.Trials_Left > 0,
							'...Standby',
							IF(@.System.EVENT.ERROR > 0,
								'Done.Error',
								'Done.Fail'
							)
						)
					)
				)),	
			c.cmd_status_inf = CONCAT_WS('->', 
				REPLACE(NULLIF(c.cmd_status_inf, ''), 'EXE...', 'EXE'), 	-- IFNULL(NULLIF(c.cmd_status_inf, ''), 'START'), 
				IF(@.System.EVENT.CALL.IS.DONE, 
					'DONE', 
					IF(@.System.EVENT.ERROR > 0,
						'ERROR',
						'FAIL'
					)
				),
				IF(c.Kind = 'Cyclic',
					'CLONE.NEW',
					NULL
				)
			),
			c.Last_Exe_AT = NOW(),
			c.Release_After = 
				IF(c.Kind = 'Cyclic',
					LEAST(c.Until_AT, NOW() + INTERVAL 10 MINUTE),
					c.Until_AT
				),
			-- c.Exe_Time_Sec = _Until_AT - _Start_AT,
			c.Exe_Time_Sec = @.System.EVENT.Run_Stop - @.System.EVENT.Run_Start,	
			c.Done_AT = IF(@.System.EVENT.CALL.IS.DONE, CURRENT_TIMESTAMP(), c.Done_AT),
			c.error = @.System.EVENT.ERROR,
			c.Trials_Log = 
				CONCAT_WS('\n', 
					CONCAT_WS(' -> ', NULLIF(c.Trials_Log, ''), @.c.cmd_status),
					IF(@.System.EVENT.CALL.IS.DONE,
						NULL,
						IF(IFNULL(@.System.EVENT.CALL.State, '') <> '', 
							@.System.EVENT.CALL.State.Trials_Log,
							IF(@.System.EVENT.ERROR > 0, 
								CONCAT(
									'ERROR: "', 
									@.System.EVENT.ERROR.MSG,
									'"'
								),
								NULL
							)
						)
					)
				),
			c.Exe_Con = 
				IF(@.System.EVENT.CALL.IS.DONE OR c.Trials_Left = 0, 
					c.Exe_Con, 
					NULL
				),
			/*
			c.Src_Session =
				IF(@.System.EVENT.CALL.IS.DONE OR c.Trials_Left = 0, 
					_Src_Session, 
					c.Src_Session
				),
			*/
			c.Trials_Left = 
				IF(@.System.EVENT.CALL.IS.DONE,
					0, 
					c.Trials_Left
				)
			/*
			c.cmd_key = 
				IF(@.System.EVENT.CALL.IS.DONE OR c.Trials_Left = 0 AND c.Cyclic_Sec > 0, 
					CONCAT('ARCH:', c.cmd_key), 
					c.cmd_key
				)
			*/
		WHERE 
			c.id = _id
		;
		
	--	Spr. @._sys_cmd.cmd_key
		IF @.NEW.cmd_key IS NOT NULL THEN
		--	For cmd_key
		/*
			UPDATE `_sys_cmd` c, `_sys_cmd` cwe
			SET
				-- c.Release_After = NOW() + INTERVAL 2 HOUR,	-- wstaw jakas a=zmiena systemowa !!!!!!!!!!!!!!!!!!!!!!!!!
				c.Release_After = NOW() + INTERVAL 10 MINUTE,		-- TEST wstaw jakas a=zmiena systemowa !!!!!!!!!!!!!!!!!!!!!!!!!
				c.cmd_status = 'ARCH',
				c.cmd_status_inf = CONCAT_WS('->', 
					c.cmd_status_inf, 
					'CLONE.NEW',
					'ARCH'
				),
				-- c.Start_AT = NULL,
				-- nie trzeba i tak obetnie do rozm. c.cmd_key = SUBSTR(CONCAT('ARCH:', c.ID, '-', c.cmd_key), 1, 100)
				c.cmd_key = CONCAT(c.ID, '.', (@._sys_cmd.cmd_key := c.cmd_key))
			WHERE
				cwe.ID = _ID
				AND cwe.cmd_key = _cmd_key -- bezp. bo moze cmd_key sie juz zmienił dla tego ID
				AND cwe.Cyclic_Sec > 0
				-- AND c.cmd_key IN (cwe.cmd_key, REPLACE(cwe.cmd_key, 'ARCH:', ''))
				AND c.cmd_key = cwe.cmd_key
				AND c.Cyclic_Sec > 0
			;
							set @.my.log = concat_WS(' / ', @.my.log, 'UPDATE:', ROW_COUNT());
		*/
			INSERT INTO `_sys_cmd`
			(cmd_key, cmd, cmd_size, cmd_status, cmd_status_inf, kind, Cyclic_Sec, Src_Session, Trials, Trials_Left, Start_AT, Until_AT, Release_After)
			SELECT
				@.NEW.cmd_key AS cmd_key, -- zapamiętany wyżej klucz!!!!
				src.cmd,
				src.cmd_size,
				'...Standby' AS cmd_status,
				'...Standby' AS cmd_status_inf,
				src.kind,
				src.Cyclic_Sec,
				src.Src_Session AS Src_Session,
				src.Trials,
				src.Trials AS Trials_Left,
				NOW() + INTERVAL src.Cyclic_Sec SECOND AS Start_AT,
				-- src.Release_After, -- = GREATEST(@._sys_cmd.Put_AT + INTERVAL 2 HOUR, IFNULL(_Release_After, '')),
				src.Until_AT,
				-- src.Release_After + INTERVAL src.Cyclic_Sec SECOND AS Release_After,
				-- src.Release_After,
				NULL AS Release_After
			FROM
			(
				SELECT
					c.cmd, c.cmd_size, c.Kind, c.Cyclic_Sec, c.Put_At, c.Src_Session, c.Trials, c.Trials_Left, c.Start_AT, c.Until_AT, c.Release_After, c.cmd_key
				FROM `_sys_cmd` c
				WHERE 
					c.id = _id
					AND c.Cyclic_Sec > 0				-- dla cyklicznych ...
					AND c.Until_AT > NOW()		-- ale nie dla tych po terminie
					-- AND c.cmd_status IN ('DONE', 'ERROR', 'FAIL')
			) src
			;
							set @.my.log = concat_WS(' / ', @.my.log, 'INSERT:', IFNULL(ROW_COUNT(), 0));

		END IF;
		
		
		
		
		
		
		
	END IF;
	
	IF _MODE IN ('ADD.CALL.State') THEN
	/************************************************************************************************
		DO _sys_cmd_ff('ADD.CALL.State', 'MANKO', 'Brak w magzynie', '', '', '');
		_ID VARCHAR(250)		- to dodawane jest do @.System.EVENT.CALL.State
		_cmd VARCHAR(250)		- to dodawane jest do @.System.EVENT.CALL.State.MSG
	************************************************************************************************/
		SET 
			@.System.EVENT.CALL.State.Trials_Log = 
				CONCAT_WS('\n', 
					@.System.EVENT.CALL.State.Trials_Log,
					CONCAT_WS(': ',
						NULLIF(_ID, ''),
						CONCAT('"', NULLIF(_cmd, ''), '"')
					)
				)
		;
	
		SET 
			@.System.EVENT.CALL.State = CONCAT_WS(' / ', @.System.EVENT.CALL.State, NULLIF(_ID, '')),
			@.System.EVENT.CALL.State.MSG = CONCAT_WS(' / ', @.System.EVENT.CALL.State.MSG, NULLIF(_cmd, ''))
		;
		SET @._sys_cmd.RETURN = @.System.EVENT.CALL.State;
	END IF;
	
	RETURN @._sys_cmd.RETURN;
END$$

DROP FUNCTION IF EXISTS `_sys_cmd_F`$$

DROP PROCEDURE IF EXISTS `_sys_cmd_event`$$
CREATE DEFINER=`root`@`localhost` PROCEDURE `_sys_cmd_event`(
	IN _MODE VARCHAR(250),
	IN _Param_A VARCHAR(255),	--	
	IN _Param_B VARCHAR(255)	--	
)
    COMMENT 'Wykonuje SQL-ki z listy zadan `_sys_cmd`'
S_sys_cmd_event: BEGIN
	IF _MODE IN ('EXE.LIST') THEN
										set @.my.log = NULL;
		DO _counters_tools('SET', '_sys_cmd_event.EXE.LIST', '', '');
		DO _sys_cmd_ff('DELETE.OLD', '', '', '', '', '');
	--	Przygotuj n rekordów do przetwarzania - UWAGA  tak kazdy rekord bedzie spr. osobno
		DROP TEMPORARY TABLE IF EXISTS `t_sys_cmd`;		-- jmam
		CREATE TEMPORARY TABLE `t_sys_cmd` (
			`i` INT(11) NOT NULL DEFAULT 0,
			`id` INT(11) NOT NULL DEFAULT 0,
			`kind` VARCHAR(50),
			`cmd` MEDIUMTEXT NOT NULL,
			`Cyclic_Sec` INT(11) DEFAULT 0 COMMENT ' gdy = 0 to zwykła jednorazowa komenda, > 0 ponawiana co jakiś czas = Cyclic_Sec od ost. zakończenia',
			`cmd_key` VARCHAR(100) DEFAULT NULL COMMENT 'Istotny przy Cyclic_Sec - symbol/klucz sql-ki - nie moze sie powtarzac!!!',
			`Src_Session` VARCHAR(250) DEFAULT '' COMMENT 'Gdy wstawiamy to "" gdy zabieramy się to wstawiamy nr sesji lub cos inego a na końcu "DONE"',
			PRIMARY KEY (`id`),
			KEY (`i`)
		)
		;
		SET @.i := 0;
		INSERT IGNORE INTO `t_sys_cmd`
			SELECT
				-- c.*
				@.i := @.i + 1 AS i, 
				sub.*
			FROM
			(
				SELECT
					-- c.*
					-- @.i := @.i + 1 AS i, 
					c.id, c.kind, c.cmd, c.Cyclic_Sec, c.cmd_key, 
					-- c.Src_Session
					sdl.GUID AS Src_Session
				FROM `_sys_cmd` c
				LEFT JOIN `_sys_db_logons` sdl ON sdl.GUID = c.Src_Session AND ! sdl.Inactive
				WHERE
					c.kind <> 'Never'
					AND c.cmd_status IN ('', '...Standby', '...Wait')
					AND c.Exe_Con IS NULL
					-- AND IFNULL(c.Exe_Con, 0) = 0 -- IS NULL
					AND c.Trials_Left > 0
					AND c.Start_AT <= NOW()
					AND c.Until_AT >= NOW()
				ORDER BY IF(c.kind = 'Cyclic', 0, 1), c.Start_AT, c.ID
			) sub
			ORDER BY i
		;
		
		SET @._sys_cmd.Let.Exe = (ROW_COUNT() > 0);
		IF @._sys_cmd.Let.Exe THEN
									set @.my.log = (SELECT GROUP_CONCAT(tc.Id) FROM `t_sys_cmd` tc);
	--	Zaczynamy .....	
		--	stworz sesje eventową
			IF @.EVENT.Session IS NULL THEN
				CALL _sessions_APP('SESSION.Born.EVENT', '', '_sys_cmd_event', '', '', '', '');
		--	zapamietaj sesję Event-ową bo sesja połączenia bezie dynamicznie zmieniana na sesję zleconego cmd o ile cmd takową wskaże!!!
				SET @.EVENT.Session = @SYSTEM.Client.Session.GUID;
												--	jmam 			CALL _exproc_LOG('LOG', CONCAT('calls.EXE.LIST: ', CONNECTION_ID(), ' -> START'), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
			END IF;
			BEGIN
				DECLARE _ID, _IS_Cyclic INTEGER;
				DECLARE _cmd_key VARCHAR(250);
				DECLARE _Src_Session, _Exe_Session VARCHAR(38);
				DECLARE _Curr_Session VARCHAR(38) DEFAULT NULL;
				DECLARE _cmd MEDIUMTEXT;
				DECLARE _error BOOL DEFAULT FALSE;
				DECLARE _empty BOOL DEFAULT FALSE;
				DECLARE c_sys_cmd CURSOR FOR
					-- było SELECT `id`, `cmd` FROM `_ToDo_call_List` WHERE `realized` IS NULL;
					-- jmam	
					SELECT 
						tc.id, tc.cmd, (tc.Cyclic_Sec > 0) AS IS_Cyclic, tc.cmd_key, tc.Src_Session
					FROM `t_sys_cmd` tc
					-- ORDER BY tc.Start_AT, tc.ID
					ORDER BY tc.i
					;	-- jmam
				DECLARE CONTINUE HANDLER FOR NOT FOUND SET _empty = TRUE;
				OPEN c_sys_cmd;
				loop1: LOOP
					FETCH c_sys_cmd INTO _ID, _cmd, _IS_Cyclic, _cmd_key, _Src_Session;
								set @.my.log = concat_WS(' / ', @.my.log, concat(_ID));
					IF _empty THEN
						set @.my.log = concat_WS(' | END at:', @.my.log, concat(_ID));
						LEAVE loop1;
					END IF;
				--	Sprawdz czy cmd - ID jest jeszcze niewykonany ...
					SET @._sys_cmd.Let.Exe = _sys_cmd_ff('Keep.1.for.Execute', _ID, '', '', '', '');
								set @.my.log = concat_WS(': ', @.my.log, @._sys_cmd.Let.Exe);
					IF @._sys_cmd.Let.Exe THEN
					--	Przygotowanie do EXE SQL
						SET 
							@.System.EVENT.ERROR = 0,
							@.System.EVENT.ERROR.MSG = NULL,
							@.System.EVENT.CALL.State = NULL,
							@.System.EVENT.CALL.State.MSG = NULL,
							@.System.EVENT.CALL.State.Trials_Log = NULL
						;
					--	jmam 	DO _counters_tools('SET', 'calls.EXE', '', '');
					--	Ustaw na chwile sesje _Src_Session polecenia (cmd) o ile jest niepusta
					--	ściślej rzecz ujmując to sklonuj ją ... ale
					--	na razie tylko ustawiaj bo klonowanie dłużej trwa
						SET _Exe_Session = IFNULL(_Src_Session, @.EVENT.Session);
						-- IF IFNULL(_Src_Session, '') <> '' 
						IF !(_Exe_Session <=> _Curr_Session) THEN
						--	klonowanie i wewn. ustawianie sesji
							--	jmam CALL _sessions_APP('SESSION.Born.As.Clone.From', '', _Src_Session, '', '', '', '');
						--	ustawianie sesji
							SET _Curr_Session = _Exe_Session;
									set @.my.log = concat_WS(' S:', @.my.log, _Curr_Session);
							CALL _sessions_APP('SET.Client.Session', _Curr_Session, '', '', '', '', '');
						END IF;
						SET @.System.EVENT.Run_Start = @@TimeStamp;
					--	EXE SQL	
						CALL _ExecuteCmd(_cmd, _error);
						SET @.System.EVENT.Run_Stop = @@TimeStamp;
							--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
							--	DO SLEEP(2);	-- sen 2 sec.
						DO _sys_cmd_ff('AFTER.EXE', _ID, '', '', '', '');
					END IF;
				END LOOP;
				CLOSE c_sys_cmd;
									set @.my.log = concat_WS(' ', @.my.log, 'EVENT-SES');
			--	Przywróć sesję EVENT-ową	
				CALL _sessions_APP('SET.Client.Session', @.EVENT.Session, '', '', '', '', '');

			END;
			IF NOT IFNULL(@session.Delfinek, FALSE) THEN
				DROP TEMPORARY TABLE IF EXISTS `t_sys_cmd`;
			END IF;
		--	zamknij sesje eventową
			CALL _sessions_APP('SESSION.Close.EVENT', '', '', '', '', '', '');	
													--	 CALL _exproc_LOG('LOG', CONCAT('calls.EXE.LIST: ', CONNECTION_ID(), ' -> END'), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
		END IF;
	END IF;
	
	
	
	

	IF _MODE IN ('TEST.OK') THEN
		SET @.System.EVENT.CALL.State = NULL;
		CALL _exproc_LOG('LOG', CONCAT_WS(', ', 'calls.EXE.LIST: proc. ', _MODE, @SYSTEM.Client.Session.GUID), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
	--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
		DO SLEEP(2);	-- sen 2 sec.
		Set @.BlaBla = '';
	END IF;
	IF _MODE IN ('TEST.FAIL') THEN
		--	SET 
		--		@.System.EVENT.CALL.State = CONCAT_WS(' / ', @.System.EVENT.CALL.State, NULLIF('Brak rekordów', '')),
		--		@.System.EVENT.CALL.State.MSG = CONCAT_WS(' / ', @.System.EVENT.CALL.State.MSG, NULLIF('Brak odpowienich zamówień', ''))
		--	;
		DO _sys_cmd_ff('ADD.CALL.State', 'Brak rekordów', 'Brak odpowienich zamówień', '', '', '');
		
		CALL _exproc_LOG('LOG', CONCAT_WS(', ', 'calls.EXE.LIST: proc. ', _MODE, @SYSTEM.Client.Session.GUID), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
	--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
		DO SLEEP(2);	-- sen 2 sec.
		/*
		SET 
			@.System.EVENT.CALL.State = 'WARRNING',
			@.System.EVENT.CALL.State.MSG = 'Brak odp. zamówień'
		;
		*/
	END IF;
	IF _MODE IN ('TEST.FAIL.2') THEN
		--	SET 
		--		@.System.EVENT.CALL.State = CONCAT_WS(' / ', @.System.EVENT.CALL.State, NULLIF('Brak rekordów', '')),
		--		@.System.EVENT.CALL.State.MSG = CONCAT_WS(' / ', @.System.EVENT.CALL.State.MSG, NULLIF('Termin realizacji', ''))
		--	;
		DO _sys_cmd_ff('ADD.CALL.State', 'Brak rekordów', 'Termin realizacji', '', '', '');
		-- CALL _exproc_LOG('LOG', CONCAT('calls.EXE.LIST: ', @.System.EVENT.CALL.State), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
		CALL _sys_cmd_event('TEST.FAIL.2.1', '', '');
	--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
		CALL _exproc_LOG('LOG', CONCAT_WS(', ', 'calls.EXE.LIST: proc. ', _MODE, @SYSTEM.Client.Session.GUID), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
		DO SLEEP(2);	-- sen 2 sec.
	END IF;
	IF _MODE IN ('TEST.FAIL.2.1') THEN
		--	SET 
		--		@.System.EVENT.CALL.State = CONCAT_WS(' / ', @.System.EVENT.CALL.State, NULLIF('MANKO', '')),
		--		@.System.EVENT.CALL.State.MSG = CONCAT_WS(' / ', @.System.EVENT.CALL.State.MSG, NULLIF('Brak w magazynie', ''))
		--	;
		DO _sys_cmd_ff('ADD.CALL.State', 'MANKO!!!', 'Brak w magazynie', '', '', '');
	--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
		DO SLEEP(2);	-- sen 2 sec.
	END IF;
	IF _MODE IN ('TEST.ERR') THEN
	--	UWAGA Sleep - skasuj po testach !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!	
		CALL _exproc_LOG('LOG', CONCAT_WS(', ', 'calls.EXE.LIST: proc. ', _MODE, @SYSTEM.Client.Session.GUID), 'EVENT', 'xxxxxx', '', @.calls.EXE.LIST.log);
		DO SLEEP(2);	-- sen 2 sec.
		SELECT k.* FROM `k_nie_ma` k WHERE k.Ilosc > 0;
	END IF;
	

	LEAVE S_sys_cmd_event;
	
END$$

DROP EVENT IF EXISTS `Event_1_minute`$$
CREATE EVENT IF NOT EXISTS `Event_1_minute`
	ON SCHEDULE 
	-- EVERY 1 MINUTE STARTS CURRENT_TIMESTAMP + INTERVAL 10 SECOND
	EVERY 30 SECOND STARTS CURRENT_TIMESTAMP + INTERVAL 10 SECOND
	DO
	BEGIN
		CALL _sys_cmd_event('EXE.LIST', '', '');
	END;
;	
$$

DELIMITER ;


/*
$Log: _sys_cmd.sql,v $
Revision 1.2  2023/06/28 18:15:36  jmam
$SEND$  usuwanie starej funkcji

Revision 1.1  2023/06/28 18:11:57  jmam
$SEND$  inicjacja


*/

/*
====================================================================================================================================================================================
	NOTATNIK
====================================================================================================================================================================================
	cmd_status:
		symb.			faza
		""				0
		"...Standby"		0
		"...Wait"			0		"Wait[(trial)]" np."Wait(2)"
		"Executing..."	1			/	"IN.PROGRESS"	/	"PROGRESS..."
		"Done"			2
		"Done.Fail"		2
		"Done.Error"	2
		"Arch.Done"			3
		"Arch.Done.Fail"	3
		"Arch.Done.Error"	3
	czyli
		IF(c.cmd_status LIKE '...%'		0
		IF(c.cmd_status LIKE '%...'		1
		IF(c.cmd_status LIKE 'Done%'	2
		IF(c.cmd_status LIKE 'Arch.%'	3
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

*/
