from django.conf import settings
from django.views.decorators.http import require_GET
from django.http import (
    HttpResponse,
    HttpResponseNotFound,
    HttpResponseServerError,
    HttpResponseRedirect,
)

from staff.gap.exceptions import GapNotFoundError
from staff.gap.controllers.gap import GapCtl
from staff.gap.workflows.utils import find_workflow

import logging
logger = logging.getLogger('staff.gap.api.views.hashed_action_views')


@require_GET
def haction(_request, haction_hash, gap_id=None):
    if gap_id is not None:
        try:
            gap = GapCtl().find_gap_by_id(gap_id)
        except GapNotFoundError:
            return HttpResponseNotFound()
    else:
        return HttpResponse(status=501)  # Not Implemented

    hactions = gap.get('hactions')
    if hactions and haction_hash in hactions:
        haction_data = hactions[haction_hash]

        workflow_cls = find_workflow(gap['workflow'])
        workflow = workflow_cls.init_to_modify(haction_data['modifier_id'], gap=gap)
        haction_method = '%s_haction' % haction_data['haction_name']
        if hasattr(workflow, haction_method):
            try:
                getattr(workflow, haction_method)(haction_hash)
            except Exception:
                logger.exception('Hash method [%s] error of changing gap[%s]' % (haction_method, gap_id))
                return HttpResponseServerError()

    gap_url = 'https://%s/gap/%s' % (settings.STAFF_DOMAIN, gap_id)
    return HttpResponseRedirect(gap_url)
