# -*- coding: UTF-8 -*-
import sys
import functools
from django.core.exceptions import ObjectDoesNotExist

from django.conf import settings
from gm_dataquery.dataquery import DataBuilder, DataSQLQuery
from gm_dataquery.db import DB

from api.models import Message

from rpc.decorators import bind

project = 'gaia'

class PrivateMessageDB(DataBuilder):
    def getval_to_user_id(self, item):
        uid = item.user_id
        status = item.conversation.user_status_set.exclude(user_id=uid).first()
        return status and status.user_id


class DB2(DB):

    def _bind(self):
        def wrap_get(params, fields):
            builder = self.builder()
            try:
                obj = self.model.objects.get(**params)
            except ObjectDoesNotExist:
                return {}
            data = builder.build_obj_data(obj, fields)
            data.pop('DT_RowId', None)
            data.pop('DT_RowData', None)
            return data

        def wrap_query(options):
            return self.sqlquery().process(**options)

        def wrap_create(**kwargs):
            return self.sqlquery().create(**kwargs)

        def wrap_update(updates, **kwargs):
            return self.sqlquery().update(updates, **kwargs)

        get_func_name = 'db_' + self.name + '_get'
        wrap_get.__name__ = get_func_name
        setattr(sys.modules[__name__], get_func_name, wrap_get)

        query_func_name = 'db_' + self.name + '_query'
        wrap_query.__name__ = query_func_name
        setattr(sys.modules[__name__], query_func_name, wrap_query)

        update_func_name = 'db_' + self.name + '_update'
        wrap_update.__name__ = update_func_name
        setattr(sys.modules[__name__], update_func_name, wrap_update)

        create_func_name = 'db_' + self.name + '_create'
        wrap_create.__name__ = create_func_name
        setattr(sys.modules[__name__], create_func_name, wrap_create)

        endpoint = functools.partial('{}/db/{}/{}'.format, self.project, self.name)
        bind(endpoint('get'))(wrap_get)
        bind(endpoint('query'))(wrap_query)
        bind(endpoint('update'))(wrap_update)
        bind(endpoint('create'))(wrap_create)


@DB2
class MessageDQ(DataSQLQuery):
    model = Message
    data_model = PrivateMessageDB
    default_using = getattr(settings, 'MESSAGE_SLAVE_DB_NAME', '')

    def filter_send_time(self, srch_key, srch_val, regex=False):
        return self._qry_time_range(srch_key, srch_val, regex)
