# -*- coding: utf-8 -*-

import logging
from collections import OrderedDict
from datetime import datetime

from django.http import Http404
from common.models import Job
from common.util.meta import escape_string
from common.util.clients import ClickhouseClient
from .base import ApiJob


class JobData(ApiJob):
    """
    Job data per second
    """
    @staticmethod
    def get(request, job, distrib_type):
        """
        :param request: http request
        :param job: job object passed from request
        :param distrib_type:
        """
        case = request.GET.get('case', '')
        overall = request.GET.get('overall', '')
        dt_from = request.GET.get('from', '')
        dt_to = request.GET.get('to', '')
        
        query_addon = ''
        if case:
            query_addon += "and tag = '{}' ".format(escape_string(case))
        if overall:
            query_addon += "and tag = '' "
        if dt_from:
            query_addon += "and time >= toDateTime('{}') ".format(datetime.strptime(dt_from, "%Y%m%d%H%M%S"))
        if dt_to:
            query_addon += "and time <= toDateTime('{}') ".format(datetime.strptime(dt_to, "%Y%m%d%H%M%S"))

        try:
            job = Job.objects.get(n=job.id)
            if not job.td:
                raise Http404('Job is online')

            ch_client = ClickhouseClient()
            query_params = job.basic_query_params.copy()
            query_params['query_addon'] = query_addon
            res = []
            if distrib_type in ['http', 'net', 'times']:
                column_header = ''
                query = ''
                if distrib_type == 'http':
                    query = '''
                            select time, tag, code, cnt
                              from loaddb.proto_codes_buffer
                              where job_id={job}
                              and job_date=toDate({job_date}) 
                                and cnt>0
                                {query_addon}
                              order by time, tag, code'''
                    column_header = 'http'
                if distrib_type == 'net':
                    query = '''
                            select time, tag, code, cnt
                              from loaddb.net_codes_buffer
                              where job_id={job}
                              and job_date=toDate({job_date}) 
                                and cnt>0
                                {query_addon}
                              order by time, tag, code'''
                    column_header = 'net'
                if distrib_type == 'times':
                    query = '''
                            select time, tag, toFloat32(bin)/1000, cnt
                              from loaddb.rt_microsecond_histograms_buffer
                              where job_id={job}
                              and job_date=toDate({job_date}) 
                                and cnt>0
                                {query_addon}
                              order by time, tag, bin'''
                    column_header = 't'
                arr = ch_client.select(query, query_params=query_params)
                if arr == ():
                    raise Http404('No data found')
                for a in arr:
                    res.append(OrderedDict([
                        ('dt', a[0]),
                        ('case', a[1]),
                        (column_header, a[2]),
                        ('cnt', a[3])
                    ]))
                return res
            if distrib_type == 'cases':
                query = '''
                        select time, tag, resps
                          from loaddb.rt_microsecond_details_buffer
                          where job_id={job}
                          and job_date=toDate({job_date}) 
                            {query_addon}
                          order by time, tag'''
                arr = ch_client.select(query, query_params=query_params)
                if arr == ():
                    raise Http404('No data found')
                for a in arr:
                    res.append(OrderedDict([
                        ('dt', a[0]),
                        ('case', a[1]),
                        ('cnt', a[2])
                    ]))
                return res
            if distrib_type == 'req_cases':
                query = '''
                        select time, tag, reqps
                          from loaddb.rt_microsecond_details_buffer
                            where job_id={job}
                            and job_date=toDate({job_date}) 
                            {query_addon}
                          order by time, tag'''
                arr = ch_client.select(query, query_params=query_params)
                if arr == ():
                    raise Http404('No data found')
                for a in arr:
                    res.append(OrderedDict([
                        ('dt', a[0]),
                        ('case', a[1]),
                        ('cnt', a[2])
                    ]))
                return res
 
        except Job.DoesNotExist:
            raise Http404('Job not found')
