from orangescape.model.engine.Component import Component
from orangescape.model.server.Context import getApplication
from orangescape.model.engine.exception.Error import InstanceNotFoundError
from orangescape.model.server.ServerError import AccessPrivilegeError,ACCESS_DENIED_MESSAGE
from RenderTemplate import renderTemplate
import urllib
from cgi import parse_qs

class BaseDataViewer:
    def __init__(self):
        self.userid=None
        self.application = getApplication()
        self.session =None
        self.component = Component(self.session)

    def initUser(self):
        guestUser = self.__get_user__()
        if guestUser:
            self.session.setUser(guestUser)
            return True
        return False

    def setSession(self,session):
        self.session=session

    def getSession(self):
        return self.session

    def setUserId(self,userId):
        self.userid=userId

    def getSheetMetadata(self,sheetMetadataName):
        return self.session.getApplication().getSheetMetadata(sheetMetadataName)

    def __get_user__(self):
        userMetadata = self.application.getSheetMetadata('User')
        try:
            guestUser = self.session.get(self.userid, userMetadata)
            isAdmin=(guestUser.getValue('IsAdmin'))
            if isAdmin :
                if isAdmin==1:
                    return guestUser
        except InstanceNotFoundError, e:
            raise AccessPrivilegeError,ACCESS_DENIED_MESSAGE %(self.userid,'User information not found in datastore!')
        self.response.out.write(ACCESS_DENIED_MESSAGE %(guestUser.getValue('FirstName'),'Administration Privileges required!'))
        return False

    def getParams(self):
        url=self.request.path
        url=urllib.unquote(url)
        path=url[1:len(url)].split('/')
        return path

    def getQueryStringParams(self, values):
        params = parse_qs(values, True)
        for key, value in params.iteritems():
                params[key] = value[0]
        return params

    def renderSheetDetailsPage(self, templateDict):
        return  renderTemplate("sheetdetails.html",templateDict, self)

    def renderSheetDataPage(self, templateDict):
        return  renderTemplate("dataviewer.html",templateDict, self)
