import logging
import datetime
import wsgiref.handlers
from google.appengine.ext import webapp
from orangescape.model.engine.exception.Error import MetadataError
from orangescape.model.server.integration.AbstractIntegrationService import AbstractIntegrationService

class FlatCsvImport(webapp.RequestHandler, AbstractIntegrationService):
    session = None
    userid=None
    def __init__(self):
        self.update = False

    def post(self,metadatatype,applicationid):
        self.initializeSession(self.userid)
        self.csvImport()
        redirectUrl = '/%s/1/administrator'%(self.session.getApplication().getSheetId())
        self.redirect(redirectUrl, True)

    def csvImport(self):
        import csv
        sheetMetadataName = self.request.get('sheetMetadataName')
        self.update = self.request.get('update')
        try:
            self.metadata = self.getSheetMetadata(sheetMetadataName)
        except MetadataError, e:
            raise e

        csvString = self.request.get("csvfile")
        csvString = csvString.encode('utf-8')
        s = csv.StringIO(csvString)
        dt = csv.DictReader(s, delimiter=",")
        self.__process__(dt)
