import json
from django.shortcuts import get_object_or_404
from django.core import serializers
from django.http import HttpResponse
from .models import Unit
from .utils import UNIT_LIST_FIELD

BAD_REQUEST = HttpResponse(json.dumps({'error': 'Bad Request'}), status=400, content_type='application/json')

def unit_json_list(request):
    ''' List Json View for local available units '''
    if request.is_ajax():
        units = Unit.objects.available_units()
        data = serializers.serialize('json', list(units), fields=UNIT_LIST_FIELD)
        _raw_data = json.loads(data)
        for unit in _raw_data:
            if unit['fields']['is_alliance']:
                unit['fields'].update({'identifier': '{}{}'.format(unit['fields']['identifier'],' (Alianza)')})
            else:
                continue
        return HttpResponse(json.dumps(_raw_data), content_type='application/json', status=200)
    else:
        return BAD_REQUEST

def detail_unit_json(request, id_unit):
    ''' Detail view of unit '''
    if request.is_ajax():
        unit = Unit.objects.filter(pk=id_unit)

        if len(unit) == 0:
            return HttpResponse(json.dumps({'error': 'Unidad no encontrada'}), status=404, content_type='application/json')

        data = serializers.serialize('json', unit, fields=UNIT_LIST_FIELD)
        # Add crew list
        _raw_data = json.loads(data)
        _raw_data[0]['fields'].update({
            'crew_list' : unit.first().get_crew_list
        })
        return HttpResponse(json.dumps(_raw_data), content_type='application/json', status=200)
    else:
        return BAD_REQUEST

def alliance_unit_json_list(request):
    ''' List Json View for alliance available units '''
    if request.is_ajax():
        units = Unit.objects.available_alliance_units()
        data = serializers.serialize('json', list(units), fields=UNIT_LIST_FIELD)
        return HttpResponse(data, content_type='application/json', status=200)
    else:
        return BAD_REQUEST

[((220, 256), 'json.dumps', 'json.dumps', (["{'error': 'Bad Request'}"], {}), "({'error': 'Bad Request'})\n", (230, 256), False, 'import json\n'), ((561, 577), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (571, 577), False, 'import json\n'), ((1257, 1316), 'django.core.serializers.serialize', 'serializers.serialize', (['"""json"""', 'unit'], {'fields': 'UNIT_LIST_FIELD'}), "('json', unit, fields=UNIT_LIST_FIELD)\n", (1278, 1316), False, 'from django.core import serializers\n'), ((1361, 1377), 'json.loads', 'json.loads', (['data'], {}), '(data)\n', (1371, 1377), False, 'import json\n'), ((1889, 1952), 'django.http.HttpResponse', 'HttpResponse', (['data'], {'content_type': '"""application/json"""', 'status': '(200)'}), "(data, content_type='application/json', status=200)\n", (1901, 1952), False, 'from django.http import HttpResponse\n'), ((838, 859), 'json.dumps', 'json.dumps', (['_raw_data'], {}), '(_raw_data)\n', (848, 859), False, 'import json\n'), ((1510, 1531), 'json.dumps', 'json.dumps', (['_raw_data'], {}), '(_raw_data)\n', (1520, 1531), False, 'import json\n'), ((1149, 1194), 'json.dumps', 'json.dumps', (["{'error': 'Unidad no encontrada'}"], {}), "({'error': 'Unidad no encontrada'})\n", (1159, 1194), False, 'import json\n')]