# -*- coding: utf-8 -*-
"""
Created on Tue Jun 04 17:10:08 2013

@author: invernizzi
"""

import sys, os, csv
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4 import QtGui, QtCore

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.figure import Figure
from Mainwindow import Ui_MainWindow

class MainForm(QtGui.QMainWindow):
    def __init__(self,parent=None):
        QtGui.QMainWindow.__init__(self)
        self.ui=Ui_MainWindow()
        self.ui.setupUi(self)
        self.data = DataHolder()
        #Add Navigation ToolBar
        self.navigationTool= NavigationToolbar(self.ui.mplwidget, self)        
        self.ui.mplLayout.addWidget(self.navigationTool)
        self.Connection()
        self.FigConfig()
        self.OnShow()
    def Connection(self):
        self.ui.actionOpen.triggered.connect(self.Open)
        self.ui.actionQuit.triggered.connect(self.close)
        self.ui.bShow.clicked.connect(self.OnShow)
        self.ui.actionSave.triggered.connect(self.OnSave)
    def FigConfig(self):
        self.fig=self.ui.mplwidget.figure
        self.axes = self.fig.add_subplot(111)   
    def OnSave(self):
        self.name=QtGui.QFileDialog.getSaveFileName(self,"")
        self.ui.mplwidget.figure.savefig(str(self.name))
    def OnShow(self):  
        self.axes.clear()
        has_series = False      
        for row in range(self.ui.listWidget.count()):
           item=self.ui.listWidget.item(row)
           name= str(item.text())
           checked=(item.checkState()==Qt.Checked)
           if checked:
                has_series = True
                x_from = self.ui.xMin.value()
                x_to = self.ui.xMax.value()
                series = self.data.get_series_data(name)[x_from:x_to + 1]
                self.axes.plot(range(len(series)), series, 'o-', label=name) 
                self.axes.hold(True)
        if (has_series and self.ui.cLegend.isChecked()):
            self.axes.legend()
        self.axes.grid() 
        self.ui.mplwidget.draw()
               
    def Open(self):
        filename = QtGui.QFileDialog.getOpenFileName(self,
            'Open a data file', '.', 'CSV files (*.csv);;All Files (*.*)')
        self.data.load_from_file(filename)
        self.fill_list(self.data.series_names())
        self.updateUi()
        self.axes.clear()
        self.axes.grid()
        self.ui.mplwidget.draw()
          
    def fill_list(self,names):
        self.ui.listWidget.clear()
        for name in names:
            item = QtGui.QListWidgetItem(name)
            item.setCheckState(Qt.Unchecked)
            self.ui.listWidget.addItem(item)
  
            
    def updateUi(self):
        if self.data.series_count() > 0 and self.data.series_len() > 0:
            self.ui.xMin.setValue(0)
            self.ui.xMax.setValue(self.data.series_len() - 1)
            
            for w in [self.ui.xMin, self.ui.xMax]:
                w.setRange(0, self.data.series_len() - 1)
                w.setEnabled(True)
        else:
            for w in [self.from_spin, self.to_spin]:
                w.setEnabled(False)
           
class DataHolder(object):
    def __init__(self, filename=None):
        self.load_from_file(filename)
    def load_from_file(self, filename=None):
        self.data = {}
        self.names = []   
        if filename:
            for line in csv.reader(open(filename, 'rb')):
                self.names.append(line[0])
                self.data[line[0]] = map(int, line[1:])
                self.datalen = len(line[1:])
    
    def series_names(self):
        """ Names of the data series
        """
        return self.names
    
    def series_len(self):
        """ Length of a data series
        """
        return self.datalen
    
    def series_count(self):
        return len(self.data)

    def get_series_data(self, name):
        return self.data[name]
        
        
if __name__=='__main__':
    app = QtGui.QApplication(sys.argv)
    mainForm=MainForm()
    mainForm.show()
    app.exec_()
