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

import wavelet
import network
import keras
import tensorflow as tf
import random



actions = [ lambda img: wavelet.rotate(img, 1)
          , lambda img: wavelet.rotate(img, 2)
          , lambda img: wavelet.rotate(img, 3)
          , lambda img: wavelet.rotate(img, 4)
          , lambda img: wavelet.rotate(img, 5)
          , lambda img: wavelet.rotate(img, 6)
          , lambda img: wavelet.rotate(img, 7)
          ]

genData = []

def blur(img):
  blured = img.copy()
  w = img.shape[1]
  h = img.shape[0]

  mx = math.sqrt(8)
  m = [(x, y, mx - math.sqrt((x*x) + (y*y))) for y in [-1,0,1] for x in [-1,0,1] ]
  s = sum([x[2] for x in m])

  for y in range(1, h - 1):
    for x in range(1, w - 1):
      v = sum([w * img[y + a, x + b] for a, b, w in m]) / s
      blured[y, x] = v
  return blured

def histogram(fileName, img):
  h = [0 for _ in range(4096)]
  for row in img:
    for v in row:
      h[max(0, min(4095, v))] += 1

  h = np.array([float(v) for v in h])
  np.save(fileName, h, allow_pickle=False)

pos = 0
first = True
with open("mimx.csv") as f:
  for row in csv.reader(f, delimiter=","):
    if first or len(row) < 9:
      first = False
      continue

    n = f"{row[2]}"
    while len(n) < 4:
      n = f"0{n}"

    fileName = f"Proband {row[0]}/SE00000{row[1]}/{row[0]}_{n}.dcm"
    print(f"{fileName}", end="\r")

    y = np.array([float(row[7]), float(row[8]), float(row[9]), float(row[10])])
    #np.save(f"{fileName}_labels.npy", y, allow_pickle=False)

    img = pydicom.dcmread(fileName).pixel_array
    #images = []
    #for action in actions:
    #  w = wavelet.refine(action(img))
    #  images.append(1.0 * w.reshape((512 * 512,)))
    #
    #images = np.array(images)
    #np.save(f"{fileName}_images.npy", images, allow_pickle=False)
    
    #np.save(f"{fileName}_plainImage.npy", img, allow_pickle=False)
    #w = wavelet.refine(img)
    #np.save(f"{fileName}_wavelet.npy", img, allow_pickle=False)

    #histogram(f"{fileName}_histogram.npy", img)

    blured = blur(img)
    np.save(f"{fileName}_blured.npy", blured, allow_pickle=False)
    histogram(f"{fileName}_blured_histo_diff.npy", np.abs(img - blured))

print()
print("done")
