# -*- coding: utf-8 -*-
"""
Created on Apr 19, 2016

@author: noob
"""
import csv
import json
import logging
import time
from comparepage.models import CompareJobsManager
from mobilecompare.models import CompareMobileJobsManager
from datetime import datetime
from django.db import connection
from django.http import HttpResponse, HttpResponseServerError, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template.context import RequestContext
from django_yauth.decorators import yalogin_required
from django_yauth.user import create_user as get_or_create_user
from .models import UISettings, Job
import settings
import requests
from .util.clients import ClickhouseClient, link_and_create_task, TaskError, CacheClient
from .util.decorators import cached
from django.db import connections
from random import choice


def get_common(request):
    user = request.yauser

    # Создаём Джанго-пользователя, если его ещё нет
    get_or_create_user(user)

    common = {}
    # ===========================================================================
    # Notification bar in header
    # ===========================================================================
    cache = CacheClient()
    common['maintenance'] = cache.get('maintenance')
    try:
        do_not_notify = cache.get('do_not_notify_{}'.format(user.login))
        if not do_not_notify:
            notification = cache.get('notification')
            assert notification
            now = time.time()
            if int(notification['expire']) > now:
                common['notify_user'] = True
                if notification['text']:
                    common['notification_text'] = '{} @{}'.format(notification['text'], notification['author'])
                else:
                    common['notification_text'] = ''
    except AssertionError:
        common['notify_user'] = False
        common['notification_text'] = ''
    except:
        logging.exception('')
        common['notify_user'] = False
        common['notification_text'] = ''
    # ===========================================================================
    try:
        common['compare_count'] = CompareJobsManager(user.login).count
    except:
        logging.exception('')
        common['compare_count'] = 0
    try:
        common['compare_mobile_count'] = CompareMobileJobsManager(user.login).count
    except:
        logging.exception('')
        common['compare_mobile_count'] = 0
    common['production_env'] = settings.ENV_TYPE == 'production'
    common['CSP_SCRIPT_NONCE'] = settings.CSP_SCRIPT_NONCE
    common['CSP_STYLE_NONCE'] = settings.CSP_STYLE_NONCE
    return common


def error_500(request):
    return render_to_response('500.html', RequestContext(request))


def check_task(request):
    try:
        task = request.GET.get('task', '')
        assert task
        link_and_create_task(request, task)
        result = True
    except (AssertionError, TaskError):
        result = False
    return HttpResponse(json.dumps(result), content_type='application/json')


@yalogin_required
def ui_set(request):
    try:
        user = request.yauser
        param = request.GET.get('param', '')
        value = request.GET.get('value', '')
        ui_setting = UISettings.objects.get_or_create(person=user.login, param=param)[0]
        ui_setting.onoff = bool(value)
        ui_setting.save()
        return HttpResponse(json.dumps([{'success': 1}]), content_type='text/json')
    except:
        logging.exception('')
        return HttpResponse(json.dumps([{'success': 0}]), content_type='text/json')


@yalogin_required
def clear_compare(request):
    try:
        job_type = request.GET.get('type', '')
        user = request.yauser
        if job_type == 'mobile':
            manager = CompareMobileJobsManager(user.login)
        else:
            manager = CompareJobsManager(user.login)
        manager.clear_jobs()

        return HttpResponse(json.dumps({'success': 1}), content_type='text/json')
    except:
        logging.exception('')
        return HttpResponse(json.dumps({'success': 0}), content_type='text/json')


@cached('st_favicon', fmt='b64')
def st_favicon():
    url = 'https://st.yandex-team.ru/favicon.ico'
    resp = requests.get(url, verify=False)
    return resp.content


def get_st_favicon(request):
    favicon = st_favicon()
    return HttpResponse(favicon)


def daily_jobs_per_project(request):
    today = datetime.today()
    year = request.GET.get('year', str(today.year))
    if not year.isdigit():
        year = today.year
    sql = '''
        select split_part(j.task, '-', 1) p, DATE(j.fd) tt, count(j.n)
        from job j
        where j.fd BETWEEN '{year}-01-01' and '{next_year}-01-01'
        group by p, tt;
    '''.format(**{'year': int(year), 'next_year': int(year) + 1})
    cursor = connection.cursor()

    try:
        cursor.execute(sql)
        data = cursor.fetchall()
    except:
        data = []
    finally:
        cursor.close()

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="jpp_{}.csv"'.format(datetime.today())

    writer = csv.writer(response)
    for value in data:
        writer.writerow(value)

    return response


def daily_mobilejobs_per_project(request):
    today = datetime.today()
    year = request.GET.get('year', str(today.year))
    if not year.isdigit():
        year = today.year
    sql = '''
        select split_part(j.task, '-', 1) p, DATE(j.fd) tt, count(j.n)
        from mobile_job j
        where j.fd BETWEEN '{year}-01-01' and '{next_year}-01-01'
        group by p, tt;
    '''.format(**{'year': int(year), 'next_year': int(year) + 1})
    cursor = connection.cursor()

    try:
        cursor.execute(sql)
        data = cursor.fetchall()
    except:
        data = []
    finally:
        cursor.close()

    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="mjpp_{}.csv"'.format(datetime.today())

    writer = csv.writer(response)
    for value in data:
        writer.writerow(value)

    return response


# redirects

@yalogin_required
def random(request):
    """
    :param request: HTTP request
    """
    sql = '''
        select n from job
    '''
    cursor = connections['default'].cursor()
    cursor.execute(sql)
    jobs = cursor.fetchall()
    jobs = [j[0] for j in jobs]
    job = choice(jobs)

    return HttpResponseRedirect("/{}".format(job))


@yalogin_required
def randa(request):
    """
    :param request: HTTP request
    """
    sql = '''
        select n from job
        where td is null
    '''
    cursor = connections['default'].cursor()
    cursor.execute(sql)
    jobs = cursor.fetchall()
    jobs = [j[0] for j in jobs]
    job = choice(jobs)

    return HttpResponseRedirect("/{}".format(job))


@yalogin_required
def last(request):
    """
    replaces old perl's /last handler
    :param request: HTTP request
    """
    user = request.yauser
    job = Job.objects.filter(person=user.login, td__isnull=False).order_by('-n')[0]
    return HttpResponseRedirect("/{}".format(job.n))


@yalogin_required
def active(request):
    """
    replaces old perl's /active handler
    :param request: HTTP request

    get param "after" - unix timestamp integer;
    """
    user = request.yauser
    job = Job.objects.filter(person=user.login, td__isnull=True).order_by('-n')
    if job:
        return HttpResponseRedirect("/{}".format(job[0].n))
    else:
        return render_to_response("active-waiter.html",
                                  RequestContext(request))
