CREATE OR REPLACE TRIGGER USR_CALLEXPORTAAF
AFTER DELETE OR INSERT OR UPDATE
ON AUTOFORNE FOR EACH ROW
DECLARE
   --pragma autonomous_transaction;
   JOB_N INT;
   V_NRAUTOFORN     AUTOFORNE.NRAUTOFORN%TYPE;
   V_CDFILDEST      AUTOFORNE.CDFILDEST%TYPE;
   V_CDFILLANC      AUTOFORNE.CDFILLANC%TYPE;
   V_IDBAIXAAF      AUTOFORNE.IDBAIXAAF%TYPE;
   V_IDINTERFACE    NUMBER;
   V_NOME           VARCHAR2(5000);
   V_COMANDO        VARCHAR2(5000);
   V_JOBISRUNNING   NUMBER;
   V_DSREMOTEADDR   VARCHAR2(15);
   V_DSREMOTEHOST   VARCHAR2(15);
   V_DSSERVERRDM    VARCHAR2(20);
   V_DSSERVMETHOD   VARCHAR2(30);
   V_DSREMOTEOPER   VARCHAR2(12);
BEGIN
   V_NRAUTOFORN := NVL(:NEW.NRAUTOFORN, :OLD.NRAUTOFORN);
   V_CDFILDEST  := NVL(:NEW.CDFILDEST, :OLD.CDFILDEST);
   V_CDFILLANC  := NVL(:NEW.CDFILLANC, :OLD.CDFILLANC);
   V_IDBAIXAAF  := :NEW.IDBAIXAAF;

   V_NOME := 'EXPORTAAF'||V_CDFILDEST||V_NRAUTOFORN;

   BEGIN
      DBMS_SCHEDULER.DROP_JOB('EXPORTAAF'||V_CDFILDEST||V_NRAUTOFORN);
   EXCEPTION
      WHEN OTHERS THEN
         NULL;
   END;

   BEGIN
      SELECT COUNT(*) INTO V_JOBISRUNNING
        FROM USER_SCHEDULER_JOBS
       WHERE JOB_NAME = V_NOME;
   EXCEPTION
      WHEN OTHERS THEN
         NULL;
   END;

   BEGIN
      WEBTUNNING(V_DSREMOTEADDR,
                 V_DSREMOTEHOST,
                 V_DSSERVERRDM,
                 V_DSSERVMETHOD,
                 V_DSREMOTEOPER);
   EXCEPTION
      WHEN OTHERS THEN
         NULL;
   END;

   IF (V_JOBISRUNNING = 0) AND (V_DSSERVMETHOD IN ('FecharAF', 'Conclui_AF')) AND V_IDBAIXAAF IS NULL THEN

      IF INSERTING THEN

         V_IDINTERFACE := 1;
         V_COMANDO := 'BEGIN USR_PROT_EXPORTA_AF('||CHR(39)||V_CDFILDEST||CHR(39)||','||CHR(39)||V_NRAUTOFORN||CHR(39)||','||CHR(39)||V_CDFILLANC||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';

         DBMS_JOB.SUBMIT(
            JOB => JOB_N,
            WHAT => V_COMANDO,
            NEXT_DATE =>SYSDATE + INTERVAL '60' SECOND);
      END IF;

      IF UPDATING THEN

         V_IDINTERFACE := 2;
         V_COMANDO := 'BEGIN USR_PROT_EXPORTA_AF('||CHR(39)||V_CDFILDEST||CHR(39)||','||CHR(39)||V_NRAUTOFORN||CHR(39)||','||CHR(39)||V_CDFILLANC||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';

         DBMS_JOB.SUBMIT(
            JOB => JOB_N,
            WHAT => V_COMANDO,
            NEXT_DATE =>SYSDATE + INTERVAL '60' SECOND);
      END IF;

      IF DELETING THEN

         V_IDINTERFACE := '3';
         V_COMANDO := 'BEGIN USR_PROT_EXPORTA_AF('||CHR(39)||V_CDFILDEST||CHR(39)||','||CHR(39)||V_NRAUTOFORN||CHR(39)||','||CHR(39)||V_CDFILLANC||CHR(39)||','||CHR(39)||V_IDINTERFACE||CHR(39)||'); END;';

         DBMS_JOB.SUBMIT(
            JOB => JOB_N,
            WHAT => V_COMANDO,
            NEXT_DATE =>SYSDATE + INTERVAL '60' SECOND);
         
      END IF;
   END IF;
END;
/

-- VERSAO --
BEGIN ATUVEROBJ('USR_CALLEXPORTAAF','6.35.038'); END;
/
