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

"""
Created on May 20, 2013

@author: noob
"""

import logging
from json import dumps

from django.http import HttpResponse
from django.http import HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response, render
from django.template import RequestContext
from django_yauth.decorators import yalogin_required

from common.views import get_common
from .. import util
from .plots.plots_base import ComparePlot


@yalogin_required
def comparepage(request):
    """

    :param request: Http Request
    """
    user = request.yauser
    common_data = get_common(request)
    try:
        if request.GET.get('jobs', ''):
            job_objects = util.get_job_objects([job.strip() for job in request.GET.get('jobs', '').split(',')])
        else:
            job_objects = util.get_user_compare_job_objects(user)

        return render_to_response('comparepage.html', {
            'pagename': 'comparepage',
            'user': user,
            'common': common_data,
            'jobs': job_objects,
            'jobs_numbers': ','.join(str(job.n) for job in job_objects),
            'colors': {job_objects[i].n: ComparePlot.color_mapping(i) for i in range(len(job_objects))},
        }, RequestContext(request))
    except:
        logging.exception('Could not render comparepage for user %s due to:', user.login)
        return HttpResponseServerError()


@yalogin_required
def no_compare_jobs(request):
    common_data = get_common(request)
    return render(request, 'error.html', {'common': common_data, 'error': 'no_compare_jobs'})


@yalogin_required
def compare_jobs(request):
    """
    called from frontend if no jobs were specified in request params, and hash was corrupted
    :param request: Http Request
    """
    user = request.yauser
    job_objects = util.get_user_compare_job_objects(user)
    job_numbers = ','.join([str(job.n) for job in job_objects])
    job_numbers = {'jobs': job_numbers}
    return HttpResponse(dumps(job_numbers), content_type='application/json')


@yalogin_required
def reset_jobs(request):
    """
    called from frontend to set jobs from hash
    :param request: Http Request
    """
    try:
        user = request.yauser
        jobs = request.POST.get('jobs', '')
        jobs = util.get_job_objects(jobs.split(','))
        manager = util.CompareJobsManager(user.login)
        manager.set_jobs([j.id for j in jobs])
        return HttpResponse(dumps({'success': 1, 'count': manager.count}), content_type='application/json')
    except Exception as exc:
        logging.exception('Could not reset jobs to compare due to:', exc_info=True)
        return HttpResponse(dumps({'success': 0, 'error': exc}), content_type='application/json')


@yalogin_required
def add_jobs_to_compare(request):
    """
    for the form on error page;
    :param request: HTTP request
    """
    try:
        user = request.yauser
        jobs = request.POST.get('jobs', "")
        errorpage = request.POST.get('errorpage', "")  # FIXME убрать логику редиректа в js на click кнопки
        job_objects = util.get_job_objects(jobs.split(','))
        manager = util.CompareJobsManager(user.login)
        manager.add_jobs([j.id for j in job_objects])
        if errorpage:
            return HttpResponseRedirect('/compare/')
        else:
            return HttpResponse(dumps({'success': 1, 'count': manager.count}), content_type='application/json')
    except Exception as exc:
        logging.exception('Could not add jobs to compare due to:', exc_info=True)
        return HttpResponseServerError(dumps({'success': 0, 'error': exc}), content_type='application/json')


@yalogin_required
def remove_jobs_to_compare(request):
    """
    for the form on error page;
    :param request: HTTP request
    """
    try:
        user = request.yauser
        jobs = request.POST.get('jobs', '')
        job_objects = util.get_job_objects(jobs.split(','))
        manager = util.CompareJobsManager(user.login)
        manager.remove_jobs([j.id for j in job_objects])
        return HttpResponse(dumps({'success': 1, 'count': manager.count}), content_type='application/json')
    except Exception as exc:
        logging.exception('Could not add jobs to compare due to:', exc_info=True)
        return HttpResponseServerError(dumps({'success': 0, 'error': exc}), content_type='application/json')


@yalogin_required
def clear_jobs_to_compare(request):
    """
    :param request: HTTP request
    """
    try:
        user = request.yauser
        manager = util.CompareJobsManager(user.login)
        manager.clear_jobs()
        return HttpResponse(dumps({'success': 1, 'count': manager.count}), content_type='application/json')
    except Exception as exc:
        logging.exception('Could not add jobs to compare due to: %s', exc_info=True)
        return HttpResponseServerError(dumps({'success': 0, 'error': exc}), content_type='application/json')
