import imp
import random

class IF:
    def __init__(self,MT):
        print "Microtubule object:",MT
        self.MT=MT
        self.maxcrosslinks=0
        self.cellarea = 1
    def IFStep(self,frame=-1):
        self.cellarea = self.MT.Params.GetParameter('CellArea')*self.MT.Params.GetParameter('CellAreaScale')
        if self.MT.Params.GetParameter('InCorticalLayer')==False:
            totlength=self.MT.ReturnTotalLength()
            print "Sub cortical length:",totlength
            if totlength>self.MT.Params.GetParameter('SubCorticalMaxLength')*self.cellarea: self.MT.Params.SetParameter(['CatastropheProbability',10])
            elif totlength<0.5: self.MT.Params.SetParameter(['CatastropheProbability',0])
        if random.random()<self.MT.Params.GetParameter('SpontaneousNucleationProbability')*self.cellarea and self.MT.Params.GetParameter('InCorticalLayer')==True  and self.MT.TotalMicrotubuleCount()<300:
            self.MT.AddRandomMT()
    def MicrotubuleIF(self,mt,mtnumber,totallength,maximumlength,frame=-1):
        mt.SaveMTCoordinates()
        mt.StepForward(totallength,maximumlength)
        collobject=self.MT.CheckSpecificCollision(mtnumber)
        if collobject.HitSomething()==True:
            mt.RestoreMT()
            decision=self.MT.ZipperDecision(collobject)
            if decision=='Zipper': mt.Zipper(collobject.angle2)
            elif decision=='ReverseZipper': mt.ReverseZipper(collobject.angle2)
            elif decision=='Catastrophe': mt.HaveCatastrophe()
            elif decision=='Sever': self.MT.SeverMicrotubule(collobject)
            else: mt.Pause()
        if self.MT.Params.GetParameter('InCorticalLayer')==True:
            try: currentcat=mt.CatastropheProbability
            except: currentcat=0
            crossovers=self.MT.OtherFaceMTs.CountMTCrossovers(mt.Coordinates)
            newcatrate=self.MT.Params.GetParameter('CrossoverBase')**crossovers/1000.0
            if currentcat<newcatrate: mt.CatastropheProbability = newcatrate
        if random.random()<0.01 and self.MT.Params.GetParameter('InCorticalLayer')==False:
            collobject=self.MT.OtherFaceMTs.CheckLinesCollisionWithPopulation(mt.Coordinates)
            if collobject.HitSomething()==False:
                self.MT.OtherFaceMTs.MTcollection.append(mt)
                del self.MT.MTcollection[mtnumber]
        if self.MT.Params.GetParameter('InCorticalLayer')==False and random.random()<self.MT.Params.GetParameter('SubCorticalSpawnProbability')*mt.Length():
            self.MT.SpawnMT()
        if self.MT.Params.GetParameter('InCorticalLayer')==True and random.random()<self.MT.Params.GetParameter('CorticalSpawnProbability')*mt.Length():
            self.MT.SpawnMT()
        if mt.SmallMT()==True or self.MT.Cell.Polygon.CheckInsideCell2(mt.tempcoords)==False:
            try:
                mt.PrepareToDie()
                del self.MT.MTcollection[mtnumber]
            except:
                pass
