import re
import csv
import grok
import cPickle
import zope.xmlpickle
from cStringIO import StringIO
from xml.dom.minidom import Document, getDOMImplementation
from zope.interface import Interface
from waeup.sirp.csvfile.interfaces import ICSVFile
from waeup.sirp.interfaces import (IWAeUPObject, IWAeUPExporter, IWAeUPXMLExporter,
                              IWAeUPXMLImporter, IWAeUPCSVImporter)

def readFile(f):
    """read a CSV file"""
    headers = []
    rows = []
    f = csv.reader(f)
    headers = f.next()
    for line in f:
        rows.append(line)
    return (headers, rows)

def writeFile(data):
    writer = csv.writer(open("export.csv", "wb"))
    writer.writerows(data)

class Exporter(grok.Adapter):
    """Export a WAeUP object as pickle.

    This all-purpose exporter exports attributes defined in schemata
    and contained objects (if the exported thing is a container).
    """
    grok.context(IWAeUPObject)
    grok.provides(IWAeUPExporter)

    def __init__(self, context):
        self.context = context

    def export(self, filepath=None):
        if filepath is None:
            filelike_obj = StringIO()
        else:
            filelike_obj = open(filepath, 'wb')
        exported_obj = cPickle.dump(self.context, filelike_obj)
        filelike_obj.close()
        return filelike_obj

class XMLExporter(grok.Adapter):
    """Export a WAeUP object as XML.

    This all-purpose exporter exports XML representations of pickable
    objects.
    """
    grok.context(Interface)
    grok.provides(IWAeUPXMLExporter)

    def __init__(self, context):
        self.context = context
    
    def export(self, filepath=None):
        pickled_obj = cPickle.dumps(self.context)
        result = zope.xmlpickle.toxml(pickled_obj)
        if filepath is None:
            filelike_obj = StringIO()
        else:
            filelike_obj = open(filepath, 'wb')
        filelike_obj.write(result)
        filelike_obj.seek(0)
        return filelike_obj

class XMLImporter(grok.Adapter):
    """Import a WAeUP object from XML.
    """
    grok.context(Interface)
    grok.provides(IWAeUPXMLImporter)

    def __init__(self, context):
        self.context = context
    
    def doImport(self, filepath):
        xml = None
        if isinstance(filepath, basestring):
            xml = open(filepath, 'rb').read()
        else:
            xml = filepath.read()
        obj = zope.xmlpickle.loads(xml)
        return obj


class CSVImporter(grok.MultiAdapter):
    grok.adapts(ICSVFile, IWAeUPObject)
    grok.provides(IWAeUPCSVImporter)
    grok.baseclass()  # We don't want this base to be registered really.

    def __init__(self, csvfile, receiver):
        self.csvfile = csvfile
        self.receiver = receiver

    def doImport(self):
        pass
