from sqlalchemy import Column, Integer, String, Boolean, DateTime, Text, ForeignKey, Index, TIMESTAMP

from datetime import datetime
class MyBase(object):
    id = Column(Integer, primary_key=True)
    created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
    updated_at = Column(TIMESTAMP, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    def __json__(self):
        if self.__jsonattrs__ is None:
            return self.__schema__().dump(self)[0]
        else:
            return self.__schema__(only=self.__jsonattrs__).dump(self)[0]
#    def __init__(self, data={}):
#        self.update(data,False)
        
    def update(self,data, partial=True):
        data, errors=self.__schema__( only=self.__whiteattrs__).load(data, partial=partial)
        if len(errors)>0:
            print errors
            return (False,errors)
        else:
            for a in self.__whiteattrs__:
                if data.has_key(a):
                    setattr(self,a,data[a])
            return (True, [])

    @classmethod
    def deserialize(cls,data):
        data, errors=cls.__schema__().load(data,partial=True)
        a=cls()
        for c in cls.__table__.columns:
            if data.has_key(c.key):
                setattr(a, c.key,data[c.key])
        return a

class MyBase2(object):
    id = Column(Integer, primary_key=True)
#    created_at = Column(TIMESTAMP, default=datetime.utcnow, nullable=False)
#    updated_at = Column(TIMESTAMP, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
    def __json__(self):
        if self.__jsonattrs__ is None:
            return self.__schema__().dump(self)[0]
        else:
            return self.__schema__(only=self.__jsonattrs__).dump(self)[0]
#    def __init__(self, data={}):
#        self.update(data,False)
        
    def update(self,data, partial=True):
        data, errors=self.__schema__( only=self.__whiteattrs__).load(data, partial=partial)
        if len(errors)>0:
            print errors
            return (False,errors)
        else:
            for a in self.__whiteattrs__:
                if data.has_key(a):
                    setattr(self,a,data[a])
            return (True, [])

    @classmethod
    def deserialize(cls,data):
        data, errors=cls.__schema__().load(data,partial=True)
        a=cls()
        for c in cls.__table__.columns:
            if data.has_key(c.key):
                setattr(a, c.key,data[c.key])
        return a
    
