import os
import sys
import glob
import math
import csv

import matplotlib.pyplot as plt
from matplotlib.tri import triplot
from matplotlib.pyplot import savefig

import numpy as np

from mimo_sequence.mimo_sequence import MimoSequence 
#import wfdb
from data_io import _rdsamp

#
#  MimoWfdbAdaptor: a class to adapt wfdb data to a mimo_sequence
#
class MimoWfdbAdaptor:
  def __init__(self):
    self.mimo = []
    #self.target_filename = 'REFERENCE.csv'
    self.target_filename = 'REFERENCE-v2.csv'
    self.labels = ['~', 'N', 'A', 'O']
    self.label_map = {}
    self.init_label_map()
  
  def init_label_map(self):
    for i in range(len(self.labels)):
      self.label_map[self.labels[i]] = i 
    print(self.label_map)

  def plot_input(self, signal, tag):
      plt.plot(signal, 'r', label="Train", linewidth = 1)
      
      plt.ylabel('ECG')
      plt.xlabel('Sample')
        
      savefig('Input' + tag +'.pdf', bbox_inches='tight')
      plt.clf()
  
  def read(self, filename):
    #sig, fields = wfdb.rdsamp(filename)
    sig, fields = _rdsamp.rdsamp(filename)
    #print(fields)  
    #print(sig)  
    #print(sig.shape[0])
    #self.plot_input(sig, fields['filename'][0])
    return sig, fields
  
  def plot_histogram(self, x):
    # a histogram of the sequence lengths
    n, bins, patches = plt.hist(x, 50, alpha=0.75)
    
#     # add a 'best fit' line
#     y = mlab.normpdf( bins, mu, sigma)
#     l = plt.plot(bins, y, 'r--', linewidth=1)
    
    plt.xlabel('Sequence length')
    plt.ylabel('Incidence')
    #plt.title(r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
    #plt.axis([40, 160, 0, 0.03])
    plt.grid(True)
    
    #plt.show()    
    savefig('sequence_len_hist.pdf', bbox_inches='tight')              
    plt.clf()


  def read_all(self, dir, fileLimit=None, pad_target=False, out_dec_factor=1):
    tag = 'allData'
    self.mimo = MimoSequence(tag, n_input_dim=1, n_output_dim = 1, max_length=None, 
                              labels=self.labels, add_pad_label=True, out_dec_factor=out_dec_factor)
    self.read_input(dir, fileLimit=fileLimit)
    self.plot_histogram(self.mimo.sequence_lengths)
    
    self.read_targets(dir, self.mimo, fileLimit, pad_target)
    self.mimo.my_display()
    gothere = True
        
  def read_targets(self, dir, mimo, fileLimit=None, pad_target=False):
    print('Reading targets from :' + dir + '\\' + self.target_filename)
    with open(dir + '\\' + self.target_filename, newline='') as csvfile:
      target_reader = csv.reader(csvfile, delimiter=',', quotechar='|')
      i_file = 0
      for row in target_reader:
        print(', '.join(row))
        print(row)
        mimo.append_target(self.label_map[row[1]], pad_target)
        i_file += 1
        print(i_file)
        if fileLimit is not None and i_file >= fileLimit:
          break

  def read_input(self, dir, fileLimit=None):
    allfiles = glob.glob(dir + "/*.mat")
    nFiles = len(allfiles)
    print('Directory : ' + dir + ' contains ' + str(nFiles) + ' files')
    self.read_input_common(allfiles, fileLimit=fileLimit)

  def read_single_input(self, filename, fileLimit=None, pad_target=False, out_dec_factor=1):
    print('Fileset is a single file: ' + filename)
    tag = 'singleFile'
    self.mimo = MimoSequence(tag, n_input_dim=1, n_output_dim = 1, max_length=None, labels=self.labels, out_dec_factor=out_dec_factor, add_pad_label=True)
    self.read_input_common([filename], fileLimit=None)

  def read_input_common(self, allfiles, fileLimit=None):
    nFiles = len(allfiles)
    iFile = 0;
    if fileLimit is not None:
      nFiles = min(nFiles, fileLimit)
    
    print('Processing ' + str(nFiles) + ' of them')      
    for iFile in range(nFiles):
      curFile = allfiles[iFile]
      name = os.path.splitext(curFile)[0]      
      #noPath=os.path.basename(curFile)
      #fileNoExt = os.path.splitext(noPath)[0]
      currInput, curFields = self.read(name)
      
#       input.append(currInput)      
#       inputLengths.append(len(currInput))      
#       ids.append(os.path.basename(name))
      tag = os.path.basename(name)
      self.mimo.append_input(currInput, tag)
      print(' Processed: ' + name + ', ' + str(len(currInput)) + ' samples')
    
    return 

      
     
    
if __name__ == '__main__':
  cm = MimoWfdbAdaptor()
  cm.read_all(sys.argv[1], int(sys.argv[2]))
