# -*- coding: UTF-8 -*-
from datetime import date
from django.db.models import Q
from gm_dataquery.dataquery import DataBuilder
from gm_dataquery.dataquery import DataSQLQuery
from api.models import BusinessKPIData
from gm_dataquery.db import DB

from themis.models import Team


class BusinessKPIDataDB(DataBuilder):

    def getval_kpi_date_month(self, obj):
        return obj.kpi_date.strftime('%Y-%m')

    def getval_group(self, obj):
        team = Team.objects.filter(id=obj.advertisement_group).first()
        return team.name if team else ''


@DB
class BusinessKPIDataDQ(DataSQLQuery):
    model = BusinessKPIData
    data_model = BusinessKPIDataDB

    def filter_kpi_date(self, srch_key, srch_val, regex):
        q = Q(kpi_date__gte=date(*[int(item) for item in srch_val[0].split('-')])) & Q(kpi_date__lte=date(*[int(item) for item in srch_val[-1].split('-')]))
        return q
