@JOBID int, @MAXLEVELS int
AS
BEGIN
SET NOCOUNT ON
SET XACT_ABORT ON

/*
declare @JOBID int
declare @MAXLEVELS int
Set @JOBID = 7
Set @MAXLEVELS = 100

exec  [dbo].[EZViewer_CA7_Get_Available_SCHID] 1000, 100
*/


DECLARE @StartNode int
DECLARE @UniqueID int = 0
DECLARE @RC int = 0
DECLARE @LEVEL int = 1

DECLARE @Rn INT; 
DECLARE @JobTrgId INT; 
DECLARE @OutSchidId INT;
DECLARE @Lv INT;
DECLARE @Pathid INT;
DECLARE @i INT;
DECLARE @JobSrcId INT;

SET @StartNode = @JOBID
SET @MAXLEVELS  = COALESCE(@MAXLEVELS, 100)
IF @MAXLEVELS > 1000 Set @MAXLEVELS = 1000


         IF OBJECT_ID('tempdb..#Discovered') IS NOT NULL DROP TABLE #Discovered
         CREATE TABLE #Discovered (
							 src int,
							 tgt int,
							 ord int,
							 ssid int,
							 tsid int,
							 pathid int  )

        CREATE NONCLUSTERED INDEX ncidx12 ON #Discovered (src ASC, tgt ASC)



        IF OBJECT_ID('tempdb..#TempDiscovered') IS NOT NULL DROP TABLE #TempDiscovered
        CREATE TABLE #TempDiscovered (
							 rn  INT IDENTITY(1,1) NOT NULL,
							 src int,
							 tgt int,
							 ord int,
							 ssid int,
							 tsid int,
							 pathid int )

       CREATE NONCLUSTERED INDEX ncidx13 ON #TempDiscovered (PathID ASC) INCLUDE (rn)




		  IF OBJECT_ID('tempdb..#Path') IS NOT NULL DROP TABLE #Path
		  CREATE TABLE #Path (
						  firstLevel int,
						  dupsch int,
						  pathid int,
						  src int,
						  tgt int,
						  ord int,
						  ssid int,
						  tsid int   )

		 CREATE CLUSTERED INDEX cidx13 ON #Path (PathID ASC, Ord ASC)

		  IF OBJECT_ID('tempdb..#alljobs') IS NOT NULL DROP TABLE #alljobs
		  CREATE TABLE #alljobs (
			  jobid int )





	   INSERT INTO #Discovered (src, tgt, ord, pathid) VALUES (@StartNode, null, 0, @UniqueID)
	   INSERT INTO #Path (src, tgt, ord, pathid) VALUES (@StartNode, null, 0,  @UniqueID)



	   SET @RC = 1
	   WHILE @RC > 0 and @MAXLEVELS > @LEVEL
	   BEGIN
		      SET @LEVEL = @LEVEL + 1
		      SET @UniqueID = 1 + (SELECT MAX(pathid) FROM #Path)
  
			 INSERT INTO #TempDiscovered (src, tgt, ord, ssid, tsid, pathid)
			 SELECT  e.TriggeredBy_JobID,
				    e.JobID,
				    MIN(d.ord) + 1,
				    e.inSCHID,
				    e.outSCHID,
				    d.pathid
		      FROM CA7_JobsTriggeredByJobs e
				  INNER JOIN #Discovered d ON d.src = e.JobID AND (    
				                                                       e.outSCHID = 0
												            OR d.ssid = 0
													       OR d.tsid IS NULL
													       OR d.ssid = e.outSCHID
														  )
			WHERE NOT EXISTS
							 (
								SELECT 1
								FROM #Discovered AS dd
								WHERE e.TriggeredBy_JobID = dd.src
									   AND e.JobID = dd.tgt
							 )
		  GROUP BY  e.TriggeredBy_JobID,
						 e.JobID,
						 e.inSCHID,
						 e.outSCHID,
						 d.pathid
           ORDER BY e.TriggeredBy_JobID

           declare cc3 cursor 
           for select rn,src,tgt,tsid,ord,pathid FROM #TempDiscovered
           OPEN cc3
           FETCH NEXT FROM cc3 INTO @Rn, @JobSrcId, @JobTrgId, @OutSchidId, @Lv, @Pathid;

           WHILE @@FETCH_STATUS = 0  
           BEGIN 
                SET @i = 0;
                IF OBJECT_ID('EZViewer_CA7_Validate_SCHID') IS NOT NULL
                    BEGIN
                        exec @i = EZViewer_CA7_Validate_SCHID @StartNode, @JobSrcId, @JobTrgId, @OutSchidId, @lv, @Pathid 
                    END

                if (@i = 0)
                BEGIN
                    delete from #TempDiscovered where rn = @Rn
                END

                FETCH NEXT FROM cc3 INTO @Rn, @JobSrcId, @JobTrgId, @OutSchidId, @Lv, @Pathid;
            END;

            CLOSE cc3
            DEALLOCATE cc3

            SET @RC = (select count(*) from #TempDiscovered)

		 INSERT INTO #Path (pathid, src, tgt, ord, ssid, tsid)
		 SELECT 
			   td.rn + @UniqueID,
			   p.src, p.tgt, p.ord, p.ssid, p.tsid
		 FROM #Path p
			 INNER JOIN #TempDiscovered td ON p.pathid = td.pathid
         GROUP BY td.rn, p.src, p.tgt, p.ord, p.ssid, p.tsid
		 
		 
		  DELETE p
		  FROM #Path p
				INNER JOIN #TempDiscovered td ON p.pathid = td.pathid


            INSERT INTO #Path (pathid, src, tgt, ord, ssid, tsid)
		  SELECT @UniqueID +  rn, 
		        src, tgt,  ord, ssid, tsid
		  FROM #TempDiscovered
		

	   
		  INSERT INTO #Discovered (src, tgt, ord, ssid, tsid, pathid)
		  SELECT src, tgt, ord, ssid, tsid, @UniqueID + rn 
		  FROM #TempDiscovered 
	  

           TRUNCATE table #TempDiscovered
END



--select * from #Path order by pathid, ord desc
	       update #Path 
		  set firstLevel = ord
		  where ord = (select MAX(ord) from #Path as p
					   where p.pathid = #Path.pathid
					   group by p.pathid)


            set @UniqueID = 1 + (select max(pathid) from #Path)

		  insert into #Path (firstLevel, dupsch, pathid, src, tgt, ord, ssid, tsid)
		  select td.firstLevel, pp.schid, @UniqueID + td.pathid + pp.schid, td.src, td.tgt, td.ord, td.ssid, td.tsid
		  from #Path as td inner join(
		  select p.pathid, p.src, spj.schid from #Path as p
			 inner join CA7_SchedulesPerJob as spj on spj.JobID = p.src
			 where p.firstLevel is not Null
		  union
		  select  p.pathid, p.src, case when tbd.outSCHID = 0 then tbd.inSCHID else tbd.outSCHID end
			 from #Path p inner join CA7_JobsTriggeredByDatasets as tbd on tbd.JobID = p.src
			 and p.firstLevel is not null and (
				p.ssid = 0
				or p.ssid is null
				)
		  )as pp on td.pathid = pp.pathid

--select * from #Path order by pathid, ord desc

--delete from #Path where dupsch is null and pathid in
--        (select p.pathid from #Path as p  where p.ssid = 0 and p.firstLevel is not Null)


		  update #Path set ssid = -dupsch
		   from (select p.pathid as pid, p.ord as o from #Path as p  where p.firstLevel is not Null)as ppp
		   where dupsch is not null and ssid = 0 and pathid = ppp.pid and ord = ppp.o

--select 'a', * from #Path order by pathid, ord desc

		  insert into #Path (firstLevel, dupsch, pathid, src, tgt, ord, ssid, tsid)
		  select  p.firstLevel,p.dupsch, p.pathid, p.src, p.tgt, p.ord, tbj.inSCHID, p.tsid
			 from #Path p inner join CA7_JobsTriggeredByJobs as tbj on tbj.TriggeredBy_JobID = p.src
			 and p.firstLevel = 0 and p.ssid is null


--select 'b',* from #Path order by pathid, ord desc

			 delete from #Path where firstLevel = 0 and ssid is null and dupsch is null

			 update #Path set ssid = -dupsch where ord = 0 and dupsch is not null and firstLevel is not null

--select * from #Path order by pathid, ord desc 



       IF OBJECT_ID('tempdb..#tmpPaths') IS NOT NULL DROP TABLE #tmpPaths
	   CREATE TABLE #tmpPaths (    
						  Row INT IDENTITY(1,1) NOT NULL PRIMARY KEY,
						  pathid int,
						  ord int,
						  ssid int,
						  tsid int)


	   INSERT INTO #tmpPaths (pathid, ord, ssid, tsid)
	   SELECT DISTINCT pathid, ord, ssid, tsid
	   FROM #Path 
	   ORDER BY pathid, ord DESC



  
			 --select * from #tmpPaths    
			 declare @forcedSchid int
			 Declare @row int
			 Declare @mxrow int
			 Set @mxrow = (select MAX(Row) from #tmpPaths)
			 Declare @cpath int
			 Declare @opath int
			 Declare @cssid int
			 Declare @ctsid int
			 Declare @otsid int
			 Declare @mval int
			 Declare @cord int
			 Set @opath = -1
			 Set @cpath = -1
			 Set @forcedSchid = 0
			 Set @otsid = @forcedSchid
			 Set @mval = @forcedSchid
			 Set @row = 1
			 while (@row <= @mxrow)
			 begin
    
				select @cpath = t.pathid, @cord = t.ord, @cssid = t.ssid, @ctsid = t.tsid
				    from #tmpPaths as t where Row = @row
				if (@opath = -1) begin
				    Set @opath = @cpath
				    Set @otsid = @cssid
				    end
				if (@cpath <> @opath)
				   begin
				    Set @opath = @cpath
				    Set @otsid = @cssid
				    Set @mval = @forcedSchid
				   end
 
				    if (@cssid = 0)
					  begin
					    update #Path set ssid = @mval where pathid = @cpath and ord = @cord
					  end
				    else
					   begin
					    if (abs(@cssid) <> abs(@otsid))
						   begin
							 delete from #Path where pathid = @cpath and ord > @cord
						   end
					    else
						  Set @mval = -abs(@cssid)
					   end
				    if (@ctsid = 0)
					   begin
						update #Path set tsid = @mval where pathid = @cpath and ord = @cord
					   end
				    else
					   begin
						  Set @mval = -abs(@ctsid)
						  Set @otsid = @ctsid
					   end        


				Set @row = @row + 1   
			 end
                   
--select * from #Path order by pathid, ord desc



		  insert into #alljobs
		  select  src as jobid from #Path
		  union
		  select  tgt as jobid from #Path
    



		  select schid 
		  from (
		  select  abs(ssid) as schid from #Path where ssid <> 0
		  union
		  select  abs(tsid) as schid from #Path where tsid <> 0
		  union 
		  select jtd.inSCHID as schid from #alljobs as j
				  inner join CA7_JobsTriggeredByDatasets as jtd 
					  on jtd.JobId = j.jobid
		  union
		  select  jtd.outSCHID as schid from #alljobs as j
				  inner join CA7_JobsTriggeredByDatasets as jtd 
					  on jtd.JobId = j.jobid
		  union
		  select SCHID as schid from CA7_SchedulesPerJob
					  where CA7_SchedulesPerJob.JobID = @JOBID
		  ) as t
		  where schid is not null and schid <> 0
		  order by schid



		  DROP TABLE #Discovered
		  DROP TABLE #Path
		  DROP TABLE #TempDiscovered
		  DROP TABLE #alljobs
		  DROP TABLE #tmpPaths

END