import logging
from google.appengine.ext import db


from orangescape.model.engine.util.NumericUtil import is_a_number
from orangescape.model.server.util.listutil import split_seq
from orangescape.model.server.Constants import GFS_MAX_COMMIT_SIZE
from orangescape.model.server.Data import PrimaryData

def __is_valid_keyname__(keyName):
    if keyName is None or len(str(keyName))==0 or is_a_number(str(keyName)[0]):# or (len(keyName)>1 and keyName[:2]=='__' and keyName[-2:]=='__'):
        return False
    return True

def get(key_names):
    return PrimaryData.get_by_key_name(key_names)

def put(entities):
    if isinstance(entities, list):
        size = len(entities)
        keyList = list()
        if size>0:
            if size > GFS_MAX_COMMIT_SIZE:
#                logging.info('Split and Commiting %d models'%(size))
                splitList = split_seq(entities, GFS_MAX_COMMIT_SIZE)
                for objList in splitList:
#                    logging.info('Commiting part %d models'%(len(objList)))
                    keyList.extend(db.put(objList))
            else:
#                logging.info('Commiting %d models'%(size))
                keyList = db.put(entities)
        return keyList
    else:
        db.put(entities)

def delete(entities):
    size = len(entities)
    if size>0:
        if size > GFS_MAX_COMMIT_SIZE:
            splitList = split_seq(entities, GFS_MAX_COMMIT_SIZE)
            for models in splitList:
                db.delete(models)
        else:
            db.delete(entities)
def put_async_write(entities):
    logging.info('async write')
    logging.info(entities)
    if isinstance(entities, list):
        size = len(entities)
        keyList = list()
        if size>0:
            if size > GFS_MAX_COMMIT_SIZE:
#                logging.info('Split and Commiting %d models'%(size))
                splitList = split_seq(entities, GFS_MAX_COMMIT_SIZE)
                for objList in splitList:
                   logging.info('Commiting part %d models'%(len(objList)))
                   db.put_async(objList)
            else:
               logging.info('Commiting %d models'%(size))
               key = db.put_async(entities)
    else:
        db.put_async(entities)
        logging.info('put_async')