import nibabel as nib

from os import path
from os.path import isdir
import os
import numpy as np
import json

def read_metadata(path_to_nii=None):
  nii=nib.load(path_to_nii)
  data=nii.get_fdata()
  max=np.max(data)
  min=np.min(data)
  return {
    'max': max,
    'min': min
  }

file_path = path.dirname(path.abspath(__file__))
root_dir=path.join(file_path, '../..')

path_to_nii=path.join(root_dir, 'output/data')
path_to_metadata=path.join(root_dir, 'output/metadata')

dirs=os.listdir(path_to_nii)

for dir in dirs:
  print(f'processing {dir}')

  os.makedirs(path.join(path_to_metadata, dir), exist_ok=True)

  files=os.listdir(path.join(path_to_nii, dir))
  for file in files:
    path_to_map=path.join(path_to_nii, dir, file)
    metadata=read_metadata(path_to_map)
    with open(path.join(path_to_metadata, dir, f'{file}.json'), 'w', encoding='utf-8') as fp:
      json.dump(metadata, fp, indent=2, ensure_ascii=False)
