from django.shortcuts import render, redirect, get_object_or_404
from pathlib import Path
import markdown
import os
from .models import NoticeBoard, IPManagementRecord


def hello_view(request):
    return render(
        request,
        "butler/landing.html",
    )


# --- notice ---
def notice_view(request):
    records = NoticeBoard.objects.all()
    return render(request, "butler/notice.html", {"records": records})


def notice_detail_view(request, pk):
    try:
        notice = NoticeBoard.objects.get(pk=pk)
    except NoticeBoard.DoesNotExist:
        return render(request, "404.html")  # 선택적으로 에러 처리

    return render(request, "butler/notice_detail.html", {"notice": notice})


# --- ip management ---
def ip_mgmt_view(request):
    # records = IPManagementRecord.objects.all()
    if request.user.is_authenticated:
        records = IPManagementRecord.objects.filter(author=request.user).order_by(
            "ip_addrs"
        )
    else:
        # records = IPManagementRecord.objects.none()
        records = IPManagementRecord.objects.all().order_by("ip_addrs")
    return render(request, "butler/ip_mgmt.html", {"records": records})


def add_ip_record(request):
    if request.method == "POST":
        network_nm = request.POST.get("network_nm")
        ip_addrs = request.POST.get("ip_addrs")
        svr_nm = request.POST.get("svr_nm")
        desc = request.POST.get("desc")
        remark = request.POST.get("remark")
        # 작성자 (author)는 로그인된 사용자로 설정
        author = request.user
        # 데이터 저장
        IPManagementRecord.objects.create(
            network_nm=network_nm,
            ip_addrs=ip_addrs,
            svr_nm=svr_nm,
            desc=desc,
            remark=remark,
            author=author,
        )
        return redirect("/ip_mgmt")


def delete_ip_records(request):
    print(f"삭제동작")
    if request.method == "POST":
        selected_ids = request.POST.getlist("selected_records")
        if selected_ids:
            IPManagementRecord.objects.filter(id__in=selected_ids).delete()
    return redirect("/ip_mgmt")


def edit_ip_record(request, pk):
    print(f"수정동작")
    record = get_object_or_404(IPManagementRecord, pk=pk)
    if request.method == "POST":
        # 디버깅 메시지 추가
        # print(f"체크: {request.POST}")
        record.network_nm = request.POST.get("network_nm")
        record.ip_addrs = request.POST.get("ip_addrs")
        record.svr_nm = request.POST.get("svr_nm")
        record.desc = request.POST.get("desc")
        record.remark = request.POST.get("remark")
        record.save()
        return redirect("/ip_mgmt")
    return render(request, "butler/ip_mgmt.html", {"record": record})


# --- privacy
def privacy_view(request):
    # 'docs/privacy.md' 파일을 읽기
    file_path = os.path.join("docs", "docs_md_files/privacy.md")
    with open(file_path, "r", encoding="utf-8") as file:
        text = file.read()

    file_path = Path('docs/docs_md_files/privacy.md')

    with file_path.open('r', encoding='utf-8') as file:
        text = file.read()
    # Markdown을 HTML로 변환
    # html_content = markdown.markdown(text)
    # Markdown을 HTML로 변환, tables 확장 활성화
    html_content = markdown.markdown(
        text,
        extensions=[
            "tables",  # 테이블 지원 확장
        ],
    )

    # 변환된 HTML을 템플릿에 전달
    return render(request, "butler/privacy.html", {"content": html_content})


def test_view(request):
    return render(
        request,
        "butler/test.html",
    )
