import mne
from mne.report import Report
import os
import json
import numpy as np
from lxml.html import parse
import hashlib
from Products.ERP5Type.Log import log

CHUNK_SIZE = 200000

def getMNEReportJSON(file_name):
  try:
    pattern = file_name + "_raw.fif"
    report_file = file_name + 'report.html'
    os.rename(file_name, pattern)
    report = Report(verbose=True)
    report.parse_folder(data_path="./", pattern=[pattern])
    report.save(report_file, overwrite=True, open_browser=False)
    data = {}
    doc = parse(report_file)
    results = doc.xpath("//table[@class = 'table table-hover']")
    rows = iter(results[0])
    for row in rows:
      data[row[0].text] = row[1].text
    json_data = json.dumps(data)
    return json_data
  except Exception as e:
    log("Error while getting JSON Report: " + str(e))
    return ""
  finally:
    if os.path.exists(pattern):
      os.rename(pattern, file_name)
    if os.path.exists(report_file):
      os.remove(report_file)

def generateSizeHash(content):
  file_name = "sample.txt"
  with open(file_name, 'wb') as afile:
    afile.write(content)
  size = os.path.getsize(file_name)
  with open(file_name, 'rb') as afile:
    file_content = afile.read()
  hash_value = hashlib.md5(file_content).hexdigest()
  if os.path.exists(file_name):
    os.remove(file_name)
  return size, hash_value

def generateRawData(sample_data_stream):
  log("-TEST- Getting raw content from sample data stream...")
  content = sample_data_stream.getData()
  file_name = "sample_data_stream_raw.fif"
  with open(file_name, 'wb') as fif_file:
    fif_file.write(content)
  try:
    raw = mne.io.read_raw_fif(file_name)
  except Exception as e:
    log("-TEST- Error getting raw data from file. Please check that sample_data_stream content corresponds to a valid fif raw file.")
    raise e

  json_data = getMNEReportJSON(file_name)

  log("-TEST- Generating array from raw content...")
  picks = mne.pick_types(raw.info)
  data, times = raw[picks]
  array = np.zeros(data.shape)
  for pick in xrange(0, len(picks)):
    data, times = raw[pick]
    array[pick] = data[0]

  if os.path.exists(file_name):
    os.remove(file_name)
  log("-TEST- Done.")
  return content, array, json_data
