from __future__ import generators
from javax.swing import JTable
from javax.swing.table import AbstractTableModel, DefaultTableColumnModel, TableColumn
from edu.sc.seis.fissuresUtil.flow.extractor.event import RegionNameExtractor
from edu.sc.seis.fissuresUtil.flow import Receiver

class Selection:
    def __init__(self, table):
        self.table = table
    
    def __len__(self):
        return self.table.getSelectedRowCount()
    
    
    def __getitem__(self, key):
        if key >= len(self):
            raise IndexError()
        count = 0
        for ev in self:
            if count == key:
                return ev
            count += 1 
    
    def __iter__(self):
        selmodel = self.table.getSelectionModel()
        start = selmodel.minSelectionIndex
        stop = selmodel.maxSelectionIndex + 1
        for i in range(start, stop):
            if selmodel.isSelectedIndex(i):
                yield self.table.model.events[i]
        
        

class EventTable(JTable):
    def __init__(self, eventList):
        cm = ColumnModel()
        dm = DataModel(eventList, cm)
        JTable.__init__(self, dm, cm)
        self.selection = Selection(self)
        

class DataModel(AbstractTableModel, Receiver):
    def __init__(self, eventList, columnModel):
        self.events = eventList
        self.columns = columnModel
        self.events.addReceiver(self)
        
    def receive(self, message):
        self.fireTableDataChanged()
        
    def getRowCount(self):
        return len(self.events)
    
    def getColumnCount(self):
        return len(columns)
    
    def getValueAt(self, row, column):
        return self.columns[column].extract(self.events[row])
    
class ColumnModel(DefaultTableColumnModel):
    def __init__(self, columns=None):
        DefaultTableColumnModel.__init__(self)
        if columns is None:
            columns = [RegionColumn()]#TODO, Magnitude(), Time(), Depth(), Latitude(), Longitude(), Catalog(), Contributor()]
        for column in columns:
            DefaultTableColumnModel.addColumn(self, column)

    def __getitem__(self, index):
        return DefaultTableColumnModel.getColumn(self, index)

class RegionColumn(TableColumn):
    def __init__(self):
        TableColumn.__init__(self)
        TableColumn.setHeaderValue(self, 'Region')
        self.extract = RegionNameExtractor().extract
        
     
