from datetime import datetime

from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods

from ..utils.draft_storage import (atomic_operation, cleanup_expired,
                                   read_drafts, write_drafts)


@login_required
@require_http_methods(["POST"])
def save_draft(request):
    model = request.POST.get('model')
    obj_id = request.POST.get('object_id', 'new')
    title = request.POST.get('title', '')
    content = request.POST.get('content', '')
    user_id = str(request.user.id)

    @atomic_operation
    def _save():
        drafts = read_drafts()
        # 组织结构
        model_data = drafts.setdefault(model, {})
        user_data = model_data.setdefault(user_id, {})
        # 存储或删除草稿
        if title or content:
            user_data[obj_id] = {
                'title': title,
                'content': content,
                'timestamp': datetime.now().isoformat()
            }
        elif obj_id in user_data:
            del user_data[obj_id]
        write_drafts(drafts)
        return JsonResponse({'status': 'success'})

    return _save()


@login_required
@require_http_methods(["GET"])
def load_draft(request):
    model = request.GET.get('model')
    obj_id = request.GET.get('object_id', 'new')
    user_id = str(request.user.id)

    @atomic_operation
    def _load():
        drafts = cleanup_expired(read_drafts())  # 加载时自动清理过期
        write_drafts(drafts)  # 保存清理后的数据
        # 提取当前草稿
        draft = drafts.get(model, {}).get(user_id, {}).get(obj_id)
        return JsonResponse(draft or {'exists': False})

    return _load()


@login_required
@require_http_methods(["POST"])
def draft_clear(request):
    model = request.POST.get('model')
    obj_id = request.POST.get('object_id')  # 可选参数
    user_id = str(request.user.id)

    @atomic_operation
    def _clear():
        drafts = read_drafts()

        # 定位到当前用户的模型数据
        model_data = drafts.get(model, {})
        user_drafts = model_data.get(user_id, {})

        if obj_id:  # 清除特定对象的草稿
            if obj_id in user_drafts:
                del user_drafts[obj_id]
                # 如果当前对象是唯一数据，则清理空容器
                if not user_drafts:
                    del model_data[user_id]
                    if not model_data:
                        del drafts[model]
        else:  # 清除整个模型类别的草稿
            if user_id in model_data:
                del model_data[user_id]
                if not model_data:
                    del drafts[model]

        write_drafts(drafts)
        return JsonResponse({'status': 'success', 'cleared': True})

    return _clear()


@login_required
@require_http_methods(["POST"])
def draft_delete(request):
    model = request.POST.get('model')
    obj_id = request.POST.get('object_id')  # 必要参数
    user_id = str(request.user.id)

    @atomic_operation
    def _delete():
        drafts = read_drafts()

        try:
            # 三级定位：model → user → object
            user_drafts = drafts[model][user_id]
            if obj_id in user_drafts:
                del user_drafts[obj_id]

                # 清理空容器
                if not user_drafts:  # 如果该用户在该模型下无草稿
                    del drafts[model][user_id]
                    if not drafts[model]:  # 如果该模型下无用户数据
                        del drafts[model]

                write_drafts(drafts)
                return JsonResponse({'status': 'success', 'deleted': True})

            return JsonResponse({
                'status': 'error',
                'msg': 'Draft not found'
            },
                                status=404)

        except KeyError:  # 处理路径不存在的情况
            return JsonResponse({
                'status': 'error',
                'msg': 'Draft not exist'
            },
                                status=404)

    return _delete()
