from app import db, app_log
from app.handler.error_handler import NotFound
from app.model.city import City
from app.model.region import Region
from app.model.country import Country
from app.model.status import Status

from app.model.units import Units
from app.model.label import Label
from app.model.categories import Categories
from app.model.resource_set import ResourceSet
from app.model.receipt import Receipt
from app.model.data import Data
from app.model.link_rs_data import LinkRsData
from app.model.user_info import UserInfo
from app.model.user_account import UserAccount

__author__ = 'Xiaoxiao.Xiong'


class DBHelper(object):
    """
    Database handler, do CRUD
    """

    def __init__(self):
        pass

    @staticmethod
    def set_user(obj):
        """
        Insert a user account into table UserAccount.
        :param obj: Json, {username:'', password:''}
        :return: Object, if insert successfully return an instance of UserAccount , otherwise return None
        """
        try:
            user = UserAccount(**obj)
            db.session.add(user)
            db.session.commit()
            return user
        except Exception as e:
            db.session.rollback()
            # app_log.error(repr(e), extra={'sender': 'DataSource'})
            raise e

    @staticmethod
    def check_username(username):

        try:
            account = UserAccount.query.filter_by(username=username).first()
            if account is not None:
                return False
            else:
                return True
        except Exception as e:
            # app_log.error(repr(e), extra={'sender': 'DataSource'})
            raise e

    @staticmethod
    def get_ext_id(obj):
        """
        Check a user account.
        :param obj: Json, {username:'', password:''}
        :return: Object/String, if account existing return ext_id, otherwise return None
        """
        try:
            account = UserAccount.query.filter_by(username=obj['username']).first()
            if account is None:
                return None
            
            if account.password == obj['password']:
                return account.ext_id
            else:
                return None
        except Exception as e:
            # app_log.error(repr(e), extra={'sender': 'DataSource'})
            raise e

    @staticmethod
    def get_user_id(ext_id):
        """
        Get user_id via ext_id
        :param ext_id: String
        :return: Boolean/String
        """
        try:
            account = UserAccount.query.filter_by(ext_id=ext_id).first()
            if account is not None:
                return account.id
            else:
                return False
        except Exception as e:
            # app_log.error(repr(e), extra={'sender': 'DataSource'})
            raise e

    @staticmethod
    def check_token(ext_id):
        """
        Inspect whether ext_id is existing
        :param ext_id: String, unique identity, which like both OpenID and Token
        :return: Boolean if ext_id existing return True, otherwise return False
        """
        try:
            flag = UserAccount.query.filter_by(ext_id=ext_id).first()

            if flag is None or not flag:
                return False
            else:
                return True

        except Exception as e:
            # app_log.error(repr(e), extra={'sender': 'DataSource'})
            raise e

    @staticmethod
    def set_info(email):
        """
        Insert an info record into UserInfo table
        :param email: String
        :return:
        """
        try:
            obj = UserInfo.query.filter_by(email=email).first()
            if obj is not None:
                return obj
            else:
                info = UserInfo(email)
                db.session.add(info)
                db.session.commit()
                return info
        except Exception as e:
            db.session.rollback()