CREATE OR ALTER trigger tbprogramacao_bu0 for tbprogramacao
active before update position 0
AS
DECLARE VARIABLE CONFLITO varchar(50);
declare variable tempo integer;
begin

  IF ( NEW.FERRAMENTA_ID > 0 ) THEN
  BEGIN

    if(old.status = 2 AND new.status = 1)then
    begin

        DELETE FROM TBREGISTRO_SETUP N
                WHERE 1=1
                AND N.TALAO_ID = new.tabela_id
                AND N.REQUISICAO = new.status_requisicao
                AND N.DATAHORA_FIM IS NULL;

    end

    --registra parada altomatica da estacao
    if((old.status = 0 AND new.status = 2) or (old.status = 1 AND new.status = 2) )then
    begin

        tempo = coalesce((select first 1
            datediff(minute,p.hora_registro,current_timestamp)
            from tbregistro_parada p
            where true
                and p.vinculo_id    = new.gp_id
                and p.subvinculo_id = new.up_id
                and p.tabela_id     = new.estacao
            order by p.hora_registro desc),0);

        if(tempo > 0)then
        begin
            --adicionar regsitro de parada inicio
            INSERT INTO TBREGISTRO_PARADA
            (
                TABELA_ID,
                TABELA,
                STATUS,
                VINCULO_ID,
                SUBVINCULO_ID,
                DATA_REGISTRO,
                HORA_REGISTRO,
                OPERADOR_ID,
                OBSERVACAO
            ) VALUES (
            new.estacao,
            'ESTACAO',
            50,
            new.gp_id,
            new.up_id,
            current_date,
            dateadd(minute,(:tempo * -1),current_timestamp),
            2715,
            NULL
            );
            --adicionar regsitro de parada fim
            INSERT INTO TBREGISTRO_PARADA
            (
                TABELA_ID,
                TABELA,
                STATUS,
                VINCULO_ID,
                SUBVINCULO_ID,
                DATA_REGISTRO,
                HORA_REGISTRO,
                OPERADOR_ID,
                OBSERVACAO
            ) VALUES (
            new.estacao,
            'ESTACAO',
            0,
            new.gp_id,
            new.up_id,
            current_date,
            current_timestamp,
            2715,
            NULL
            );

        end

    end

  END

end;

