import os
import mne
import json
from DateTime import DateTime
from mne.report import Report
#from Products.ERP5Type.Log import log

def getHTMLReport(file_name, raw):
  try:
    pattern = file_name + "_raw.fif"
    report_file = file_name + 'report.html'
    report = Report(verbose=True)
    report.parse_folder(data_path="./", pattern=[pattern])
    report.save(report_file, overwrite=True, open_browser=False)
    with open(report_file, 'r') as report:
      content = report.read()
    os.remove(report_file)
    return content
  except Exception as e:
    return str(e)

def getJSONMetadata(raw_info):
  info = { 'filename': 'FILENAME', #raw_info['filename'],
           'nchan': raw_info['nchan'],
           'ch_names': raw_info['ch_names'],
          'sfreq': raw_info['sfreq']
          }
  return json.dumps(info)

def getRawData(file_name, data_stream_content):
  with open(file_name, 'wb') as fif_file:
    fif_file.write(data_stream_content)
  raw = None
  try:
    raw = mne.io.read_raw_fif(file_name, preload=True)
  except:
    pass
  if raw is None:
    try:
      raw = mne.io.read_raw_edf(file_name, preload=True)
    except:
      pass
  return raw

def processRawData(data_stream, data_array, data_descriptor):
  file_name = "temporal_file_%s" % DateTime().strftime('%Y%m%d-%H%M%S')
  try:
    data_stream_content = data_stream.getData()
    raw_file = file_name + "_raw.fif"
    raw = getRawData(raw_file, data_stream_content)
    if raw is None: raise StandardError("the file does not contain raw data.")
    json_metadata = getJSONMetadata(raw.info)
    html_report = getHTMLReport(file_name, raw)
    data_descriptor.setTextContent(json_metadata)
    data_descriptor.setTextContent(html_report)
    #log("Data Descriptor metadata: " + str(data_descriptor.getTextContent()))
    data_array.setArray(raw._data)
    #log("Data Array array: " + str(data_array.getArray()))
    os.remove(raw_file)
    return "Raw data processed."
  except Exception, e:
    if os.path.exists(raw_file):
      os.remove(raw_file)
    return "Error while processing raw data: " + str(e)
