import DICOMWeb from '../../../DICOMWeb';

/**
 * Function to get series sequence (sequence of pepeating items where each
 * item includes the attributes of one or more series) based on a given sopInstance.
 *
 * @param {Object} instance The sop instance
 * @returns {Promise} Referenced series sequence
 */
const getReferencedSeriesSequence = instance => {
  const referencedSeriesSequenceRaw = instance['00081115'];

  const referencedSeriesSequence = [];

  if (referencedSeriesSequenceRaw && referencedSeriesSequenceRaw.Value) {
    referencedSeriesSequenceRaw.Value.forEach(referencedSeries => {
      const referencedSeriesInstanceUID = DICOMWeb.getString(
        referencedSeries['0020000E']
      );

      const referencedInstanceSequenceRaw = referencedSeries['0008114A'];
      const referencedInstanceSequence = [];

      referencedInstanceSequenceRaw.Value.forEach(referencedInstance => {
        referencedInstanceSequence.push({
          referencedSOPClassUID: DICOMWeb.getString(
            referencedInstance['00081150']
          ),
          referencedSOPInstanceUID: DICOMWeb.getString(
            referencedInstance['00081155']
          ),
        });
      });

      referencedSeriesSequence.push({
        referencedSeriesInstanceUID,
        referencedInstanceSequence,
      });
    });
  }

  return referencedSeriesSequence;
};

export default getReferencedSeriesSequence;

@@ -823,16 +823,61 @@
  = %5B%5D;%0A%0A
+      if (referencedInstanceSequenceRaw) %7B%0A  
       re
@@ -942,32 +942,34 @@
 ce =%3E %7B%0A        
+ 
+ 
 referencedInstan
@@ -978,32 +978,34 @@
 Sequence.push(%7B%0A
+  
           refere
@@ -1033,32 +1033,34 @@
 MWeb.getString(%0A
+  
             refe
@@ -1088,35 +1088,39 @@
 150'%5D%0A          
+  
 ),%0A
+  
           refere
@@ -1163,32 +1163,34 @@
 ng(%0A            
+  
 referencedInstan
@@ -1206,35 +1206,51 @@
 155'%5D%0A          
+  
 ),%0A
+          %7D);%0A
         %7D);%0A    
@@ -1245,25 +1245,23 @@
     %7D);%0A
+
       %7D
-);
 %0A%0A      

handle missing ReferencedInstanceSequence attribute (#2786)