# $CVSHeader: pal8e/src/Sheet.py,v 1.13 2005/02/15 01:10:26 indraneel Rel $

import os
import time

from Element import PSSDElement, PSSDElements

class PSSDSheet(PSSDElements):
    def __init__(self, logger):
        self.logger = logger
        PSSDElements.__init__(self, logger)

    def _broken(self, elemi, elemj):
        if elemi in elemj.pairs: return None
        if (elemi.end() in elemj.start().prev[:2]) or \
               (elemi.end() in elemj.start().next[:3]):
            return 'Broken'
        return None

    def _get_broken_pairs(self):
        broken_pairs = []
        self.sort_by_position()
        for i in range(len(self)-1):
            if self._broken(self[i], self[i+1]):
                broken_pairs.append([self[i], self[i+1]])
        return broken_pairs

    def _propagate_brks(self):
        broken_pairs = self._get_broken_pairs()
        if not broken_pairs: return
        for pairs in broken_pairs:
            for pair in pairs:
                pair.log('broken in same sheet')
        
    ## Public Methods

    def grow(self, strand):
        strand.tag = 1
        self.append(strand)
        for pair in strand.pairs:
            if pair.tag == None:
                self.grow(pair)

    def interpret(self):
        self.link_back()
        self.link_back_pairs()
        self._propagate_brks()
        return [self]
        
    def setID(self, sheetID):
        self.sheetID = sheetID
        for strand in self:
            strand.sheetID = sheetID

class PSSDSheets(list):
    def __init__(self, logger):
        self.logger = logger

    ## Public Methods

    def log(self):
        for sheet in self:
            self.logger.log('element', 'Sheet: '+sheet.sheetID)
            sheet.log()

    def set_sheetID(self):
        sheetID = 1
        for sheet in self:
            sheet.setID(str(sheetID))
            sheetID += 1

    def interpret(self, definition):
        definition.pairup_strands()
        for elem in definition:
            if elem.type == 'E':
                elem.tag = None
        sheets = []
        for elem in definition:
            if elem.type != 'E': continue
            if elem.tag == None:
                sheet = PSSDSheet(self.logger)
                sheet.grow(elem)
                sheets.append(sheet)
        for sheet in sheets:
            self += sheet.interpret()
        self.set_sheetID()
        self.logger.log('info', 'Sheets Interpreted')
