import pydicom
import numpy as np
import matplotlib.pyplot as plt
import os
import csv

table = {}

header = "Proband,SE,Image,min,max,minD,maxD,cont_val,blur_val,art_val,plan_val"
print(header)

with open("overview.csv") as f:
  for row in csv.reader(f, delimiter=";"):
    if len(row) >= 20:
      k = f"{row[7]}/{row[8]}"
      table[k] = f"{row[16]},{row[17]},{row[18]},{row[19]}"



def testPicture(fileName, patientNr, seNr, n, last=None):
  if not os.path.exists(fileName):
    return None, None, None, None, None

  a = None
  b = None
  c = None
  d = None
  img = pydicom.dcmread(fileName)
  if last is not None:
    ab = np.abs(img.pixel_array)
    a = np.max(ab)
    for row in ab:
      for x in row:
        if b is None or b == 0:
          b = x
        if x > 0:
          b = min(b, x)
    

    diff = np.abs(img.pixel_array - last)
    c = np.max(diff)
    for row in diff:
      for x in row:
        if d is None or d == 0:
          d = x
        if x > 0:
          d = min(d, x)
  last = img.pixel_array
  return last, a, b, c, d


def testSe(path, patientNr, seNr):
  path = f"{path}/SE00000{seNr}"
  last = None
  for n in range(1000):
    m = f"{n}"
    while len(m) < 4:
      m = f"0{m}"
    name = f"{path}/{patientNr}_{m}.dcm"
    last, mx, mi, mxD, miD = testPicture(name, patientNr, seNr, n, last)
    if last is None:
      break
    if mx is not None:
      v = ""
      if path in table:
        v = table[path]
      print(f"{patientNr},{seNr},{n},{mi},{mx},{miD},{mxD},{v}")


def testPatient(patientNr):
  path = f"Proband {patientNr}"
  for n in [1,2,3,4,5,6,7,8]:
    testSe(path, patientNr, n)


for patientNr in ["02", "03", "04", "05", "06", "07", "08", "09", "10", "11"]:
  testPatient(patientNr)
