from bson.objectid import ObjectId

from django.contrib.auth.decorators import login_required, permission_required
from django.core.urlresolvers import reverse
from django.http import (
    HttpResponseNotFound,
    HttpResponseForbidden,
    HttpResponseServerError,
    HttpResponseRedirect,
)
from django.shortcuts import render
from django.views.decorators.http import require_http_methods


from staff.gap.controllers.templates import TemplatesCtl
from staff.gap.gap_admin.utils import (
    base_edit_template,
    base_new_template,
    edit_template_get,
    new_template_get,
    join_collection,
)
from staff.gap.gap_admin.forms import StIssueTemplateForm

import logging
logger = logging.getLogger('staff.gap.gap_admin.views.edit_st_issue_template_view')


@require_http_methods(['POST', 'GET'])
@login_required
@permission_required('gap.gap_admin')
def edit_st_issue_template(request, template_id=None):
    if not request.user.is_superuser:
        return HttpResponseForbidden()

    template_url = 'gap_admin/gap_templates/edit_st_issue.html'

    if template_id is not None:
        context = _edit_template_get(template_id)
    else:
        context = _new_template_get()

    if request.method == 'GET':
        return render(request, template_url, {'template': context})

    form = StIssueTemplateForm(request.POST)
    if form.is_valid():
        try:
            data = form.cleaned_data
            t_ctl = TemplatesCtl()
            if template_id is not None:
                template = t_ctl.find_one({'_id': ObjectId(template_id)})
                if not template:
                    return HttpResponseNotFound()
                template.update(base_edit_template(data))
                template.update(_template_data(data))
                t_ctl.update(template)
            else:
                template = base_new_template(data)
                template.update(_template_data(data))
                t_ctl.new(**template)
        except Exception:
            logger.exception('Error saving template')
            return HttpResponseServerError()

        return HttpResponseRedirect(reverse('gap-admin:list-templates'))

    return render(request, template_url, {'form': form, 'template': context})


def _edit_template_get(template_id):
    template = edit_template_get(template_id)
    if template:
        t = template['template']
        template['queue'] = t['queue']
        template['issue_type'] = t['type']['id']
        template['components'] = t['components']
        join_collection(template, 'components')
        template['summary'] = t['summary']
        template['description'] = t['description']

    return template


def _new_template_get():
    return new_template_get('st_issue', {
        'queue': '.. очередь в ST ..',
        'issue_type': '.. ID типа issue ..',
        'components': '.. ID компонентов ..',
        'summary': '.. заголовок тикета ..',
        'description': '.. описание тикета ..',
    })


def _template_data(data):
    return {
        'template': {
            'queue': data['st_issue_queue'],
            'type': {'id': data['st_issue_type']},
            'components': data['st_issue_components'],
            'summary': data['st_issue_summary'],
            'description': data['st_issue_description'],
        }
    }
