from django.shortcuts import render
from django.http import HttpResponse
from django.apps import apps
from .models import Character, PackageFeature, Feature, Pin

from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import Pin
from .serializers import PinSerializer

import json

# Create your views here.
def home(request):
    with open('test_character.json', 'r+') as file:
        character = json.load(file)

    character = Character.objects.get(name="Gerom")
    class_feature_links = (
        PackageFeature.objects
        .filter(package=character.char_class)
        .select_related('feature')
        .order_by('priority')
    )
    character.char_class.display_features = class_feature_links
    return render(request, 'main/character_sheet.html', {'character': character, })


def feature_add_view(request):
    if request.method == 'GET':
        return render(request, 'main/feature.html')
    elif request.method == 'POST':
        # Parse basic fields
        name = request.POST.get('feature_name')
        description = request.POST.get('feature_description')

        # Parse Requirements
        requirements = []
        req_keys = [k for k in request.POST.keys() if k.startswith('requirement_')]
        idxs = set()
        for k in req_keys:
            try:
                idxs.add(int(k.split('_')[-1]))
            except:
                continue
        for idx in sorted(list(idxs)):
            prop = request.POST.get(f'requirement_property_{idx}', '').strip()
            cond = request.POST.get(f'requirement_condition_{idx}', '').strip()
            val = request.POST.get(f'requirement_value_{idx}', '').strip()
            if prop and cond and val:
                requirements.append({'property': prop, 'condition': cond, 'value': val})

        # Parse Operations (with extra subparts)
        operations = []
        op_keys = [k for k in request.POST.keys() if k.startswith('operation_attr_')]
        op_idxs = [int(k.replace('operation_attr_', '')) for k in op_keys]
        for op_idx in op_idxs:
            attr = request.POST.get(f'operation_attr_{op_idx}', '').strip()
            op = request.POST.get(f'operation_operation_{op_idx}', '').strip()
            value = request.POST.get(f'operation_value_{op_idx}', '').strip()

            # Subparts/limits
            subparts = []
            sub_idx = 0
            while True:
                kfield = f'operation_{op_idx}_limitkey_{sub_idx}'
                vfield = f'operation_{op_idx}_limitval_{sub_idx}'
                if kfield in request.POST and vfield in request.POST:
                    k = request.POST.get(kfield, '').strip()
                    v = request.POST.get(vfield, '').strip()
                    if k and v:
                        subparts.append({'key': k, 'value': v})
                    sub_idx += 1
                else:
                    break
            operation = {'attr': attr, 'operation': op, 'value': value}
            for part in subparts:
                operation[part['key']] = part['value']
            operations.append(operation)

        feat = Feature.objects.create(
            feature_name=name,
            feature_description=description,
            feature_requirements=requirements,
            feature_data={'operations': operations}
        )
        return render(request, 'main/feature_add.html', {
            'msg': f'Feature "{feat.feature_name}" added successfully!',
        })

def map_page(request):
      return render(request, "main/map.html")

@api_view(['GET', 'POST'])
def pin_list(request):
    if request.method == 'GET':
        pins = Pin.objects.all()
        serializer = PinSerializer(pins, many=True)
        return Response(serializer.data)
    if request.method == 'POST':
        serializer = PinSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)