#coding=utf-8
import re
import random

from django.utils.translation import gettext as _
from django.template import loader,Context,RequestContext
from django.template.context_processors import csrf
from django.utils.http import urlquote
from django.core import serializers 
from django.http import HttpResponse,HttpResponseRedirect,Http404,JsonResponse
from django.shortcuts import get_object_or_404,get_list_or_404,render
from django.core.paginator import Paginator, InvalidPage
from django.urls import reverse

#from utils import html
from utils.email import new_comment_mail
from blog.templatetags.themes import theme_template_url
from blog import models,blog_forms
from blog.models import Post,Comments,Tags,Category,COMMENT_APPROVE_STATUS
from utils.waptools import detect_mobile

PAGE_SIZE = 10

def index(request):
    '''site index view,show 10 latest post.'''
    #detect mobile device
    mobile = None #detect_mobile(request,mobile_redirect=reverse('wap_pre'))
    #TO-DO: fix firefox with wml addone  detect
    if mobile:
        return HttpResponseRedirect(mobile)
    
    pageid = int(request.GET.get('page', '1'))
    pagedPosts = Paginator(Post.objects.all().filter(post_type__iexact = 'post',
                                      post_status__iexact = models.POST_STATUS[0][0]),
                                 PAGE_SIZE)  
                       
    return renderPaggedPosts(pageid,_('Home'),pagedPosts,True,request)

def post(request,postname=None,postid=0):
    '''get post by post name'''
    msg = None
    error = None
    if postname:
        try:
            post = get_object_or_404(Post,post_name__iexact=postname,post_type__iexact='post')
        except Http404 as e:
            #Backwards compatible handle
            postname = urlquote(postname)
            post = get_object_or_404(Post,post_name__iexact=postname,post_type__iexact='post')            
    elif int(postid)>0:
        #get by postid
        post = get_object_or_404(Post,id__exact=postid,post_type__iexact='post')
    if post:
        #post back comment
        if (post.comment_status == models.POST_COMMENT_STATUS[0][0]) or (post.comment_status == models.POST_COMMENT_STATUS[3][0]) :
            form = blog_forms.CommentForm()
        else:
            form = None
        if not request.session.get('post_hits_%s' % post.id):
            #update hits count
            post.hits = post.hits + 1
            post.save()
            request.session['post_hits_%s' % post.id] = True;  
        comments = Paginator(post.comments_set.filter(comment_approved__iexact=
                                                            COMMENT_APPROVE_STATUS[1][0]).order_by('comment_date'),
                                                            PAGE_SIZE
                                  )
        pageid = int(request.GET.get('page', 1))  
        return render((request),
                                theme_template_url()+ '/blog/post.html',
                                  {'post':post,'form':form,'msg':msg,'error':error,
                                'comments':comments.page(pageid),
                                'tab':'home'})       
    else:
        raise Http404()

def page(request,pagename):
    '''get page by page name'''
    msg = None
    error = None
    if pagename:
        try:
            page = get_object_or_404(Post,post_name__exact=pagename,post_type__iexact='page')
        except Http404 as e:
            #Backwards compatible handle
            pagename = urlquote(pagename)
            page = get_object_or_404(Post,post_name__exact=pagename,post_type__iexact='page')            
        #post back comment
        if (page.comment_status == models.POST_COMMENT_STATUS[0][0])  or (page.comment_status == models.POST_COMMENT_STATUS[3][0]) :
            form = blog_forms.CommentForm()
        else:
            form = None
        if not request.session.get('post_hits_%s' % page.id):
            #update hits count
            page.hits = page.hits + 1
            page.save()
            request.session['post_hits_%s' % page.id] = True;     
        comments = Paginator(page.comments_set.filter(comment_approved__iexact=
                                                    COMMENT_APPROVE_STATUS[1][0]).order_by('comment_date'),
                                                    PAGE_SIZE
                          )
        pageid = int(request.GET.get('page', 1))
        from templatetags.filters import pageclass
        tab = pageclass(page.id)
        
        return render((request),theme_template_url()+ '/blog/page.html',
                                  {'post':page,
                                    'form':form,
                                    'comments':comments.page(pageid),
                                    'msg':msg,
                                    'error':error,
                                    'tab': tab}
                                 )        
    else:
        raise Http404()
    
def dateposts(request,year,month,date):
    '''get posts by date'''    
    pageid = int(request.GET.get('page', '1'))
    if year:
        year = int(year)    
        if month:
            month =int(month)    
            if date:
                date =int(date)
                pagedPosts = Paginator(Post.objects.filter(
                    pubdate__year=year,
                    pubdate__month=month,
                    pubdate__day=date,
                    post_type__iexact='post',
                    post_status__iexact = models.POST_STATUS[0][0]),
                                             PAGE_SIZE)              
            else:
                #month list
                pagedPosts = Paginator(Post.objects.filter(pubdate__year=year,
                                        pubdate__month=month,
                                        post_type__iexact='post',
                                        post_status__iexact = models.POST_STATUS[0][0]),
                                             PAGE_SIZE)                
        else:
            #year list
            pagedPosts = Paginator(Post.objects.filter(pubdate__year=year,
                                    post_type__iexact='post',
                                    post_status__iexact = models.POST_STATUS[0][0]),
                                         PAGE_SIZE)
    pageTitle = '-'.join([str(year),str(month),str(date)])
    return renderPaggedPosts(pageid,pageTitle,pagedPosts,False,request)

def categoryView(request,catname=None,catid=0):
    'Return the posts in the category'
    catid=int(catid)   
    if catname:
        try:
            catInfo = get_object_or_404(Category,enname__iexact=catname)
        except Http404 as e:
            catname = urlquote(catname)            
            catInfo = get_object_or_404(Category,enname__iexact=catname)                        
    elif catid > 0:       
        #get by id      
        catInfo = get_object_or_404(Category,id__exact=catid)        
    if catInfo:
            pagedPosts = Paginator(Post.objects.filter(category__id__exact=catInfo.id,
                                        post_type__iexact = 'post',
                                        post_status__iexact = models.POST_STATUS[0][0]),PAGE_SIZE)
            pageid =  int(request.GET.get('page', '1'))       
            return renderPaggedPosts(pageid,catInfo.name,pagedPosts,False,request)           
    else:
        raise Http404()
    
def tags(request,tagname = None):
    '''get the tag related posts.'''
    msg = None
    if tagname:
        try:
            tag = get_object_or_404(Tags,slug__iexact=tagname)
        except Http404 as e:
            tagname = urlquote(tagname)
            tag = get_object_or_404(Tags,slug__iexact=tagname)
        if tag:
            pageid = int(request.GET.get('page', '1'))
            pagedPosts = Paginator(tag.post_set.all().filter(post_type__iexact='post',
                                                                   post_status__iexact = models.POST_STATUS[0][0]),
                                    PAGE_SIZE)
        return renderPaggedPosts(pageid,tag.name,pagedPosts,False,request,tab='tags')
    else:
        #taglist page    
        max = 0    
        tag = Tags.objects.all().order_by('-reference_count')[:1]
        if tag:
            max = tag[0].reference_count
        if max <=0:
            max = 1        
        tags = Tags.objects.all()
        for tag in tags:
            tag.reference_count = tag.reference_count * 10/max
        return render((request),
                                    theme_template_url()+ '/blog/tags.html',
                                  {'tags':tags,'max':max,'tab':'tags'},
                                  )

def renderPaggedPosts(pageid,pageTitle,pagedPosts,showRecent = False,request=None,tab='home'):   
    #no post return only title
    if pagedPosts.count <=0:
        return render((request),
                                theme_template_url()+ '/blog/list.html',
                                  {'pagetitle':pageTitle,'tab':tab}
                                  )
    currentPage = pagedPosts.page(pageid)
    data = {'pagetitle':pageTitle,'ol':currentPage,'tab':tab}    
    if request:
        context = (request)
    return render(context,
    theme_template_url()+ '/blog/list.html',
                              data )

def json(data):    
    return JsonResponse(data)
    # data =  serializers.serialize('json',data)    
    # return HttpResponse(data,mimetype='application/x-javascript')
    
def post_comment(request,postid):
    if not request.is_ajax():
        raise Http404    
    request.session['vcode'] = '123'
    vcode = '123' # request.POST.get('vcode')
    if vcode.lower() != request.session.get('vcode'):
        error = _('The confirmation code you entered was incorrect!')
        return json({'success':False,'error':error})
    else:                
        #set a random string to session, refresh post failed
        request.session['vcode'] = random.random()
        author = request.POST.get('author')
        email = request.POST.get('email')
        content = request.POST.get('content')
        
        url = request.POST.get('url','')
        
        post = Post.objects.get(id__exact=int(postid))
        if  post.comment_status ==  models.POST_COMMENT_STATUS[3][0]:  # comment no need approve
            comment_approved_status = models.COMMENT_APPROVE_STATUS[1][0]   # comment approved
        else:
            comment_approved_status = models.COMMENT_APPROVE_STATUS[0][0]   # comment unapproved
        comment = Comments(post = post,
                               comment_author= author,
                               comment_author_email=email,
                               comment_author_url=url,
                               comment_author_IP= user_host_address(request),
                               comment_content = content,
                               comment_approved=comment_approved_status,
                               comment_agent=request.META['HTTP_USER_AGENT'])                 
        comment.save()
        new_comment_mail(post.title,comment.comment_content)   
        return json({'success':_('Comment post successful!')})            
 
def user_host_address(request):
    """
    get user ip address
    """
    if 'HTTP_X_FORWARDED_FOR' in request.META:
        return request.META['HTTP_X_FORWARDED_FOR']
    else:
        return request.META['REMOTE_ADDR']
                 
        
