from django.shortcuts import render, redirect
from django.http import HttpResponse
from urllib.parse import unquote
from .peopleinfo import PEOPLE


def password_required(request):
    PASSWORD = '1110'  # 실제 비밀번호

    if request.method == "POST":
        entered_password = request.POST.get("password")
        if entered_password == PASSWORD:
            request.session["authenticated"] = True
            next_url = request.POST.get("next", "/")

            if not next_url:
                next_url = "/"

            return redirect(next_url)
        else:
            return render(request, "B_main/password.htm", {"error": "Incorrect password. Please try again."})
    
    # GET 요청 시 비밀번호 입력 폼 렌더링
    next_url = request.GET.get("next", "/")
    return render(request, "B_main/password.htm", {"next": next_url})


# 인증 검사 함수
def check_authentication(request):
    if not request.session.get("authenticated"):
        return redirect(f"/password/?next={request.path}")
    return None


def main(request):
    # 인증 확인
    auth_check = check_authentication(request)
    print('auth_check: ', auth_check)
    if auth_check:
        return auth_check

    def sort_key(person):
        sequence = person.get('SEQUENCE')
        # SEQUENCE가 존재하면 정수로 변환하여 가장 먼저, 없으면 무한대로 설정
        return (int(sequence) if sequence else float('inf'), person['이름'])

    sorted_people = sorted(PEOPLE, key=sort_key)

    context = {
        'people': sorted_people
    }
    return render(request, 'B_main/main.htm', context)


def vcard_download(request, name):
    # 인증 확인
    auth_check = check_authentication(request)
    if auth_check:
        return auth_check

    name = unquote(name)
    person = next((p for p in PEOPLE if p['이름'] == name), None)

    if not person:
        return HttpResponse("잘못된 이름입니다.", status=404)

    vcard_content = f"""BEGIN:VCARD
VERSION:3.0
N:{person['이름']};;;;
FN:{person['이름']}
ORG:{person['소속']}
TITLE:{person['직책']}
TEL;CELL:{person['연락처']}
ADR:;;{person['주소']}
END:VCARD
"""

    response = HttpResponse(vcard_content, content_type='text/vcard')
    response['Content-Disposition'] = f'attachment; filename="{person["이름"]}.vcf"'
    return response


def search_people(request):
    # 인증 확인
    auth_check = check_authentication(request)
    if auth_check:
        return auth_check

    query = request.GET.get('search', '').strip()

    # query가 빈 문자열이면 전체 반환
    if not query:
        filtered = PEOPLE
    else:
        filtered = [
            p for p in PEOPLE
            if query in p.get('이름', '') 
            or query in p.get('소속', '') 
            or query in p.get('직책', '') 
            or query in p.get('연락처', '') 
            or query in p.get('주소', '') 
            or query in p.get('생년월일', '')
            or query in p.get('TITLE', '')
        ]

    def sort_key(person):
        sequence = person.get('SEQUENCE')
        # SEQUENCE가 존재하면 정수로 변환하여 가장 먼저, 없으면 무한대로 설정
        return (int(sequence) if sequence else float('inf'), person['이름'])

    sorted_people = sorted(filtered, key=sort_key)


    return render(request, 'B_main/partials/card_list.htm', {'people': sorted_people})



def logout_view(request):
    request.session.flush()
    return redirect('/password/')