from Ft.Server.Server import FtServerServerException, Error
from Ft.Server.Common import ResourceTypes
from Ft.Server import FTSERVER_NAMESPACE
from Ft.Xml.XLink import XLINK_NAMESPACE
from Ft.Server.Server.Drivers.FtssDriver import DataStoreContainer

FTSS_CONTAIMENT_TABLE = 'ftss_containment'

class MySQLContainer(DataStoreContainer):
    """
    Implements simple containment as a table in MySQL:
    
    parent   /  child
    ------------------
    /parent1 |  child1
    /parent2 |  child2
    """
    def __init__(self,db):
        """
        Used if instanciated directly in order to do initialization
        """
        self._db = db
    
    def initialize(self):
        """
        Initialize the table
        """
        c=self._db.cursor()
        c.execute(CREATE_CONTAINMENT_TABLE%((FTSS_CONTAIMENT_TABLE,FTSS_CONTAIMENT_TABLE,FTSS_CONTAIMENT_TABLE)))
    
    def fetchChildren(self,parent):
        """
        Returns a list of child uris for the given parent.  Parent is a PathImp
        """        
        #from inspect import stack;from pprint import pprint;pprint(stack())
        #print "underlying container datastore implementation!"
        c=self._db.cursor()        
        c.execute("""SET AUTOCOMMIT=0""")                
        c.execute("""SELECT child FROM %s WHERE parent = '%s'"""%(FTSS_CONTAIMENT_TABLE,parent.absolutePath))
        rt=c.fetchall()
        
        if not not rt:
            return [rtItem[0] for rtItem in rt]
        else:
            return []
        
    def manageChildren(self,parent,child,add=True):
        """
        Adds/remove the child specified by the given path to the parent (path - a PathImp)
        """
        c=self._db.cursor()
        c.execute("""SET AUTOCOMMIT=0""")
        if add:
            c.execute("""INSERT INTO %s (parent,child) VALUES ('%s','%s')"""%(FTSS_CONTAIMENT_TABLE,parent.absolutePath,child))
        else:            
            c.execute("""DELETE FROM %s where parent = '%s' and child = '%s'"""%(FTSS_CONTAIMENT_TABLE,parent.absolutePath,child))
        
    

CREATE_CONTAINMENT_TABLE = """
CREATE TABLE %s (
    parent varchar(50) NOT NULL,
    child varchar(30) NOT NULL,
    UNIQUE INDEX %s_indexPC (parent(50),child(30)),
    INDEX %s_indexP (parent(50))
) TYPE=InnoDB"""
