from google.appengine.ext import webapp
from orangescape.model.server.BaseDataViewer import BaseDataViewer

import os
import logging

templatePath = os.path.join(os.path.dirname(__file__).split('model')[0],'templates')

class DataViewer(webapp.RequestHandler, BaseDataViewer):
    def __init__(self):
        BaseDataViewer.__init__(self)

    def getDetails(self,metadatatype,applicationid):
        if self.initUser():
            sheetList = self.session.getApplication().getSheetMetadataList()
            sheetNameList = sheetList.values()
            sheetNameList.sort()
            templateDict = {'sheetNameList':sheetNameList, 'applicationId':self.session.getApplication().getSheetId()}
            self.response.out.write(self.renderSheetDetailsPage(templateDict))

    def getData(self,metadatatype,applicationid,url):
        if self.initUser():
            urlList=self.getParams()
            query_string=self.request.query_string
    #        logging.info(url+"*********************************"+query_string)
            sheetMetadataName = urlList.pop()
            sheetMetadata = self.getSheetMetadata(sheetMetadataName)
            sheetMetadataId = sheetMetadata.getSheetId()
            publicCellMetadataList = sheetMetadata.getCellMetadataList()
            publicCellMetadataList.sort(lambda x, y: cmp(x.getValue('CellName'), y.getValue('CellName')))
            queryStringDict = self.getQueryStringParams(query_string)

            conditionList =  list()
            filterName = ""
            filterValue = ""
            if queryStringDict.get("filterName"):
                filterName = queryStringDict.get("filterName")

            if queryStringDict.get("filterValue"):
                filterValue = queryStringDict.get("filterValue")

            if filterValue and filterName:
                filterCell = sheetMetadata.getPublicCellMetadata(filterName)
                if not filterCell.isStr():
                    filterValue = float(filterValue)
                conditionList.append((filterCell.getSheetId(), '=',filterValue))
            if queryStringDict.get("count"):
                count = queryStringDict.get("count")
                self.response.out.write(self.session.count(sheetMetadata, ('and',conditionList)))
            else:
                #execute the query
                limit = 100
                if queryStringDict.get("limit"):
                    limit = int(queryStringDict.get("limit"))
                startValue = 0
                endValue = 0
                prevAction = "prev"
                if queryStringDict.get("nextValue"):
                    prevAction = "next"
                    startValue = int(queryStringDict.get("nextValue"))
                elif queryStringDict.get("prevValue"):
                    startValue = int(queryStringDict.get("prevValue") )- limit
                if startValue < 0:
                    startValue = 0
                baseQuery = ("and", conditionList)
                queryResult = self.session.advQuery( sheetMetadata, limit, baseQuery, None, None, False, startValue)

                if len(queryResult) > 0:
                    endValue = limit + startValue

                isSystemParam = "false"
                if  queryStringDict.get("isSystemParam"):
                    isSystemParam = queryStringDict.get("isSystemParam")

                #construct list for mako template
                cellNameList = list()
                for cell in publicCellMetadataList:
                    if isSystemParam == "false":
                        if not cell.isSystemCell():
                            cellNameList.append(cell.getCellName())
                    else:
                        cellNameList.append(cell.getCellName())

                sheetList = dict()
                editorPageUrl = "/1/"+self.session.getApplication().getSheetId()+"/"+sheetMetadataId
                for dataObject in queryResult:
                    sheetValueList = list()
                    activityId = ""
                    for cell in publicCellMetadataList:
                        if isSystemParam == "false":
                            if not cell.isSystemCell():
                                sheetValueList.append(dataObject.get(cell))
                        else:
                            sheetValueList.append(dataObject.get(cell))

                        if cell.getCellName() == 'Status':
                            activityId = dataObject.get(cell)
                            if activityId is None:
                                activityId = ""
                    sheetList[editorPageUrl+"/"+activityId+"/"+sheetMetadataId+"/"+dataObject.getSheetId()] = sheetValueList

                urlPath = self.request.path
                isValidLength = True
                if len(queryResult) < limit:
                    isValidLength = False

                templateDict = {'cellNameList':cellNameList,
                                'sheetList':sheetList,
                                'baseUrl':urlPath,
                                'limit':limit,
                                'prevValue':startValue,
                                'nextValue':endValue,
                                'isSystemParam':isSystemParam,
                                'prevAction':prevAction,
                                'isValidLength':isValidLength,
                                'filterName':filterName,
                                'filterValue':filterValue
                                }

                self.response.out.write(self.renderSheetDataPage(templateDict))
