from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from pathlib import Path
import markdown
import os
from .models import IPManagementRecord
from blog.models import Post
from board_notice.models import BoardNotice
from django.db.models import Q


class LandingPageView(TemplateView):
    template_name = "butler/landing.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # context['var'] var를 templates로 전달해서 보여지는 것.
        context['blog_posts'] = Post.objects.order_by('-created_at')[:3]
        context['board_notices'] = BoardNotice.objects.order_by('-created_at')[:3]
        return context

# --- 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(
#         records = IPManagementRecord.objects.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 ip_mgmt_view(request):
    query = request.GET.get("var_search", "").strip()
    
    records = IPManagementRecord.objects.order_by(
        "ip_addrs"
    )

    if query:
        records = records.filter(
            # Q(author__username__icontains=query) | Q(author__email__icontains=query)
            Q(author__username__icontains=query) | Q(network_nm__icontains=query)
        )
    """
    SELECT * FROM ip_management_record AS ip JOIN auth_user AS au 
    ON ip.author_id = au.id 
    WHERE au.username LIKE CONCAT('%', 조회할 값, '%') 
    OR au.email LIKE CONCAT('%', 조회할 값, '%') 
    ORDER BY ip.ip_addrs;
    """
    records = records.order_by("ip_addrs")
    return render(request, "butler/ip_mgmt.html", {"records": records, "var_search": query})


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")
        contents = request.POST.get("contents")
        remark = request.POST.get("remark")
        # 작성자 (author)는 로그인된 사용자로 설정
        author = request.user
        # 데이터 저장
        IPManagementRecord.objects.create(
            network_nm=network_nm,
            ip_addrs=ip_addrs,
            svr_nm=svr_nm,
            contents=contents,
            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)

    # 🔥 검색 키워드 유지
    var_search = request.GET.get("var_search") or request.POST.get("var_search")

    if request.method == "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.contents = request.POST.get("contents")
        record.remark = request.POST.get("remark")
        record.save()

        if var_search:
            return redirect(f"/ip_mgmt?var_search={var_search}")
        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",
    )
