# Path: jellyblog/forms.py
# class SearchForm(forms.Form):
#     search_query = forms.CharField(label="search", min_length=2, max_length=100)
# 
# Path: jellyblog/models.py
# class Category(models.Model):
#     id = models.AutoField(primary_key=True)
#     parent = models.ForeignKey('self')
#     name = models.CharField(max_length=20)
# 
#     def __init__(self, *args, **kwargs):
#         super(Category, self).__init__(*args, **kwargs)
#         self.children = []
# 
#     def __str__(self):
#         return self.name
# 
#     @classmethod
#     def sorted_category(cls):
#         return_category = list(cls.objects.all())
#         childList = []
#         for category in return_category:
#             if (category.parent.id == 1):
#                 continue
#             else:
#                 parent_index = return_category.index(category.parent)
#                 return_category[parent_index].children.append(category)
#                 childList.append(category)
# 
#         for child in childList:
#             return_category.remove(child)
# 
#         return return_category
# 
#     @classmethod
#     def init_category(cls):
#         is_empty = cls.objects.count() == 0
#         if is_empty:
#             with connection.cursor() as cs:
#                 cs.execute('INSERT INTO jellyblog_category \
#                              (name, parent_id) VALUES ("Home", 1)')
# 
# class Document(models.Model):
#     # 문서 Model
#     def __str__(self):
#         return self.title
# 
#     id = models.AutoField(primary_key=True)
#     category = models.ForeignKey(Category)
#     title = models.CharField(max_length=100)
#     content = models.TextField()
#     time = models.DateTimeField(auto_now_add=True)
#     meta_tag = models.CharField(max_length=150)
#     view_count = models.IntegerField(default=0, editable=False)
#     public_doc = models.BooleanField()
#     thumbnail = models.ImageField(null=True, upload_to="thumnail_img/")
#     update_time = models.DateTimeField(auto_now=True)
#     is_markdown = models.BooleanField()
#     linebreaks = models.BooleanField()
# 
#     def read(self):
#         self.view_count += 1
#         self.save()
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'detail', (), {'document_id': self.id}
# 
#     @classmethod
#     def search_document(cls, query):
#         if len(query) == 0:
#             return None
#         return cls.objects.filter((
#             Q(title__icontains=query) | Q(content__icontains=query))
#             & Q(public_doc=True))
# 
# Path: jellyblog/util.py
# def get_page_number_range(paginator, page):
#     # 페이지네이션의 범위를 반환해주는 함수
#     # 총 페이지 수가 10개 이하일 경우 1 ~ (총 페이지 수) 보여줌
#     if (paginator.num_pages < 11): 
#         return range(1, paginator.num_pages + 1)
# 
#     # 선택된 페이지번호가 6보다 크고
#     elif (page.number > 6): 
#         if (page.number + 4 < paginator.num_pages):
#             # {선택된 페이지번호 + 4} 페이지가 더 있을 경우 (현재 페이지 - 5) ~ (현재 페이지 + 4)까지 보여줌
#             return range(page.number - 5, page.number + 5)
#             # {선택된 페이지번호 + 4} 보단 적을 경우 (현재 페이지 - 5) ~ (총 페이지 수)까지 보여줌
#         else:
#             return range(page.number - 5, paginator.num_pages + 1)
#     # 나머지 경우에 대해선 1 ~ 10까지 보여준다.
#     else: 
#         return range(1, 11)
# 
# def get_documents(paginator, page):
#     # 각 페이지에 해당하는 문서들을 가져오는 함수
#     try:
#         documents = paginator.page(page)
#     except PageNotAnInteger:
#         documents = paginator.page(1)
#     except EmptyPage:
#         documents = paginator.page(paginator.num_pages)
#     return documents


from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from jellyblog.forms import SearchForm
from .models import Category, Document
from htmlmin.decorators import minified_response
from .util import get_page_number_range, get_documents


def init_category():
    Category.init_category()


@minified_response
def home(request):
    init_category()
    return render(request, 'jellyblog/home.html')


@minified_response
def index(request):
    return index_with_page(request, 1)


@minified_response
def index_with_page(request, page):
    document_list = Document.objects.filter(public_doc=True).order_by('-id')
    paginator = Paginator(document_list, 4)
    documents = get_documents(paginator, page)
    context = {
        'documents': documents,
        'category_list': Category.sorted_category(),

# Path: jellyblog/forms.py
# class SearchForm(forms.Form):
#     search_query = forms.CharField(label="search", min_length=2, max_length=100)
# 
# Path: jellyblog/models.py
# class Category(models.Model):
#     id = models.AutoField(primary_key=True)
#     parent = models.ForeignKey('self')
#     name = models.CharField(max_length=20)
# 
#     def __init__(self, *args, **kwargs):
#         super(Category, self).__init__(*args, **kwargs)
#         self.children = []
# 
#     def __str__(self):
#         return self.name
# 
#     @classmethod
#     def sorted_category(cls):
#         return_category = list(cls.objects.all())
#         childList = []
#         for category in return_category:
#             if (category.parent.id == 1):
#                 continue
#             else:
#                 parent_index = return_category.index(category.parent)
#                 return_category[parent_index].children.append(category)
#                 childList.append(category)
# 
#         for child in childList:
#             return_category.remove(child)
# 
#         return return_category
# 
#     @classmethod
#     def init_category(cls):
#         is_empty = cls.objects.count() == 0
#         if is_empty:
#             with connection.cursor() as cs:
#                 cs.execute('INSERT INTO jellyblog_category \
#                              (name, parent_id) VALUES ("Home", 1)')
# 
# class Document(models.Model):
#     # 문서 Model
#     def __str__(self):
#         return self.title
# 
#     id = models.AutoField(primary_key=True)
#     category = models.ForeignKey(Category)
#     title = models.CharField(max_length=100)
#     content = models.TextField()
#     time = models.DateTimeField(auto_now_add=True)
#     meta_tag = models.CharField(max_length=150)
#     view_count = models.IntegerField(default=0, editable=False)
#     public_doc = models.BooleanField()
#     thumbnail = models.ImageField(null=True, upload_to="thumnail_img/")
#     update_time = models.DateTimeField(auto_now=True)
#     is_markdown = models.BooleanField()
#     linebreaks = models.BooleanField()
# 
#     def read(self):
#         self.view_count += 1
#         self.save()
# 
#     @models.permalink
#     def get_absolute_url(self):
#         return 'detail', (), {'document_id': self.id}
# 
#     @classmethod
#     def search_document(cls, query):
#         if len(query) == 0:
#             return None
#         return cls.objects.filter((
#             Q(title__icontains=query) | Q(content__icontains=query))
#             & Q(public_doc=True))
# 
# Path: jellyblog/util.py
# def get_page_number_range(paginator, page):
#     # 페이지네이션의 범위를 반환해주는 함수
#     # 총 페이지 수가 10개 이하일 경우 1 ~ (총 페이지 수) 보여줌
#     if (paginator.num_pages < 11): 
#         return range(1, paginator.num_pages + 1)
# 
#     # 선택된 페이지번호가 6보다 크고
#     elif (page.number > 6): 
#         if (page.number + 4 < paginator.num_pages):
#             # {선택된 페이지번호 + 4} 페이지가 더 있을 경우 (현재 페이지 - 5) ~ (현재 페이지 + 4)까지 보여줌
#             return range(page.number - 5, page.number + 5)
#             # {선택된 페이지번호 + 4} 보단 적을 경우 (현재 페이지 - 5) ~ (총 페이지 수)까지 보여줌
#         else:
#             return range(page.number - 5, paginator.num_pages + 1)
#     # 나머지 경우에 대해선 1 ~ 10까지 보여준다.
#     else: 
#         return range(1, 11)
# 
# def get_documents(paginator, page):
#     # 각 페이지에 해당하는 문서들을 가져오는 함수
#     try:
#         documents = paginator.page(page)
#     except PageNotAnInteger:
#         documents = paginator.page(1)
#     except EmptyPage:
#         documents = paginator.page(paginator.num_pages)
#     return documents


# Path: jellyblog/views.py
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator
from django.conf import settings
from jellyblog.forms import SearchForm
from .models import Category, Document
from htmlmin.decorators import minified_response
from .util import get_page_number_range, get_documents



def init_category():
    Category.init_category()


@minified_response
def home(request):
    init_category()
    return render(request, 'jellyblog/home.html')


@minified_response
def index(request):
    return index_with_page(request, 1)


@minified_response
def index_with_page(request, page):
    document_list = Document.objects.filter(public_doc=True).order_by('-id')
    paginator = Paginator(document_list, 4)
    documents = get_documents(paginator, page)
    context = {
        'documents': documents,
        'category_list': Category.sorted_category(),

        'page_range': get_page_number_range(