from datetime import datetime
from application.app import db
from models.package import PackageModel
from webcreator.log import logger
from webcreator.response import ResponseCode, response_result

class PackageResource(object):
    def __init__(self):
        super().__init__()

    def get(self, uuid, params):
        # handle business
        filters = [PackageModel.is_delete==False, PackageModel.uuid==uuid]
        result = PackageModel.query.filter(*filters).first()
        if result:
            return (True, result)
        return (False, result)

    def getList(self, params):
        # handle business
        logger.warn(params)
        filters = [PackageModel.is_delete==False]
        result = PackageModel.query.filter(*filters).order_by(PackageModel.create_at).paginate(params.get('page', 1), params.get('pageSize', 10), error_out=False)

        return (True, result.items, result.total)

    def post(self, params, jwt={}):
        # handle business
        result = PackageModel.query.filter(PackageModel.app == params.get('app')).first()
        if result and result.is_delete:
            result.is_delete = False
            result.update_by = jwt.get("id", "")
            result.update_date = datetime.now()
            db.session.commit()
            return (True, None)
        elif result and result.is_delete == False:
            return (False, "record code exists")

        result = PackageModel(**params)
        db.session.add(result)
        db.session.commit()
        return (True, None)

    def put(self, uuid, params, jwt={}):
        # handle business
        result = PackageModel.query.filter(PackageModel.uuid==uuid).first()
        if not result:
            return (False, "record not exists")

        if params:
            for key, value in params.items():
                if value != None: setattr(result, key, value)
            result.update_by = jwt.get("id", "")
            result.update_date = datetime.now()
            db.session.commit()
            return (True, None)
        else:
            return (False, "params is null")

    def delete(self, uuid, jwt={}):
        # handle business
        result = PackageModel.query.filter(PackageModel.uuid==uuid).first()
        if not result:
            return (False, "record not exists")

        result.update_by = jwt.get("id", "")
        result.update_date = datetime.now()
        result.is_delete = True
        db.session.delete(result)
        db.session.commit()
        return (True, None)

packageManager = PackageResource()