from unittest import TestCase

import Zope

from Products.Squishdot import manage_addSquishdot
from Products.Squishdot.Utility import addFile, createUploadable
from OFS.Folder import Folder
from Testing.makerequest import makerequest
from AccessControl.SecurityManagement import newSecurityManager
from AccessControl.User import UnrestrictedUser


class Base(TestCase):

    def setUp(self):
        self.app = makerequest(Zope.app())
        # Log in as a god :-)
        newSecurityManager(None, UnrestrictedUser('god',
                                                  'god',
                                                  [],
                                                  ''))
        # set a URL1 for us to use
        self.app.REQUEST.set('URL1','something')

    def tearDown(self):
        get_transaction().abort()
        self.app._p_jar.close()
        
class SquishdotBase(Base):

    def setUp(self, default_doc='demo1'):
        Base.setUp(self)
        app = self.app
        try: app._delObject('squishdottest')
        except AttributeError: pass
        app.manage_addFolder('squishdottest')
        
        self.Folder = app.squishdottest

        manage_addSquishdot(self.Folder,'testSquish',default_doc=default_doc)
        self.Site = app.squishdottest.testSquish
        
    def _addPosting(self,**kw):
        Site = self.Site
        REQUEST = {}

        filepath = kw.get('filepath',None)
        if filepath is not None:
            file = createUploadable(filepath)
            del kw['filepath']
        else:
            file = ''

        object = kw.get('object',Site)
        if object is not Site:
            del kw['object']
            
        for attribute in kw.keys():
            REQUEST[attribute]=kw[attribute]
        
        return object.addPosting(file,REQUEST)

    def _getPosting(self,title=None):
        REQUEST={}
        if title is not None:
            REQUEST['title']=title
        brains = self.Site(REQUEST)
        return brains[0].getObject()

class Demo2Base(SquishdotBase):
    " Base with demo2 skin instead of demo1 "
    def setUp(self):
        SquishdotBase.setUp(self,default_doc='demo2')

class PlainBase(SquishdotBase):
    " Base with plain skin instead of demo1 "
    def setUp(self):
        SquishdotBase.setUp(self,default_doc='plain')


