DROP function IF EXISTS `vn`.`workerTimeControl_add`;

DELIMITER $$
CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT,  vWarehouseFk INT,  vTimed DATETIME,  vIsManual BOOL) RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vDirection VARCHAR(6);
	DECLARE vLastIn DATETIME;
	DECLARE vDayStayMax INT;
    DECLARE vHasDirectionOut INT;
    DECLARE vLastInsertedId INT;

    SELECT dayStayMax INTO vDayStayMax
		FROM workerTimeControlParams;
        
    SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection;

	IF vDirection = 'out' THEN
	
		SELECT MAX(timed) INTO vLastIn
			FROM workerTimeControl 
			WHERE userFk = vUserFk 
				AND direction = 'in'
				AND timed < vTimed;
	
		UPDATE  workerTimeControl wtc
			SET wtc.direction = 'middle'
			WHERE userFk = vUserFk
				AND direction = 'out'
				AND timed BETWEEN vLastIn AND vTimed;
	
	ELSE IF vDirection = 'in' THEN
			
            SELECT COUNT(*) INTO vHasDirectionOut 
				FROM workerTimeControl wtc
				WHERE userFk = vUserFk 
					AND direction = 'out'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);          

			UPDATE  workerTimeControl wtc
				SET wtc.direction = IF (vHasDirectionOut,'middle','out')
				WHERE userFk = vUserFk
					AND direction = 'in'
					AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed);  

		 END IF;
     END IF;
	
	INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual)
		VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual);
        
	SET vLastInsertedId = LAST_INSERT_ID();
    
    CALL workerTimeControlSOWP(vUserFk, vTimed);
    
	RETURN vLastInsertedId;
END$$

DELIMITER ;



DROP procedure IF EXISTS `vn`.`workerTimeControl_add`;

DELIMITER $$
CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL)
BEGIN
	
	
	SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual);
END$$

DELIMITER ;