class Category(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.CharField(max_length=50, unique=True)
    description = models.CharField(max_length=500)
    is_display = models.BooleanField(default=False)
    min_published_blogs = models.IntegerField()
    max_published_blogs = models.IntegerField()

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Category, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name

    def __str__(self):
        return self.name

    @property
    def get_url(self):
        return settings.SITE_BLOG_URL + "category/" + self.slug

    def get_blog_posts(self):
        return Post.objects.filter(category=self, status='P')

    def no_of_blog_posts(self):
        return Post.objects.filter(category=self).count() class Tags(models.Model):
    name = models.CharField(max_length=50, unique=True)
    slug = models.CharField(max_length=50, unique=True)

    def save(self, *args, **kwargs):
        tempslug = slugify(self.name)
        if self.id:
            tag = Tags.objects.get(pk=self.id)
            if tag.name != self.name:
                self.slug = create_tag_slug(tempslug)
        else:
            self.slug = create_tag_slug(tempslug)
        super(Tags, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.name class Post(models.Model):
    STATUS_CHOICE = (
                    ('D', 'Draft'),
                    ('P', 'Published'),
                    ('T', 'Rejected'),
                    ('R', 'Review'),
                    )

    title = models.CharField(max_length=100)
    created_on = models.DateTimeField(auto_now_add=True)
    updated_on = models.DateField(auto_now=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)
    content = models.TextField()
    excerpt = models.CharField(max_length=500, default="")
    category = models.ForeignKey(Category, related_name='blog_posts')
    tags = models.ManyToManyField(Tags, related_name='rel_posts', blank=True)
    status = models.CharField(max_length=2, choices=STATUS_CHOICE, blank=True)
    published_on = models.DateField(blank=True, null=True)
    meta_description = models.TextField(max_length=500, default='')
    old_slugs = models.TextField()

    def __unicode__(self):
        return self.title

    def create_blog_slug(self, slugs):
        for each_slug in list(set(slugs)):
            blog_slugs = self.slugs.filter(slug=each_slug)
            if not blog_slugs:
                actual_slug = get_blog_slug(each_slug)
                Post_Slugs.objects.create(
                    blog=self, slug=actual_slug, is_active=False
                )

    def check_and_activate_slug(self):
        # Check whether active slug is their for blog-post or not
        blog_slugs = self.slugs.all().order_by("id")
        if not blog_slugs.filter(is_active=True):
            active_slug = blog_slugs.last()
            active_slug.is_active = True
            active_slug.save()

    @property
    def slug(self):
        blog_slug = self.slugs.filter(is_active=True).first()
        if blog_slug:
            return str(blog_slug.slug)
        return ""

    @property
    def author(self):
        return self.user.first_name + ' ' + self.user.last_name

    def save(self, *args, **kwargs):
        if self.status == 'P':
            if not self.published_on:
                self.published_on = datetime.datetime.today()
        super(Post, self).save(*args, **kwargs)

    @property
    def get_url(self):
        return settings.SITE_BLOG_URL + self.slug

    def is_editable_by(self, user):
        if self.user == user or user.is_superuser:
            return True
        return False

    def is_deletable_by(self, user):
        if self.user == user or user.is_superuser:
            return True
        return False

    def get_content(self):
        table = html.fromstring(self.content)
        content = ''
        for item in table:
            if item.text:
                content += item.text.strip()
        return content[:350] class Subscribers(models.Model):
    email = models.EmailField(max_length=255)
    created = models.DateField(auto_now_add=True)
    blog_post = models.BooleanField(default=True)
    category = models.ForeignKey(Category, blank=True, null=True)

    def __str__(self):
        return self.email class Post_Slugs(models.Model):
    blog = models.ForeignKey(Post, related_name='slugs')
    slug = models.SlugField(max_length=100, unique=True)
    is_active = models.BooleanField(default=False) class Contact(models.Model):

    ENQUERY_TYPES = (
                    ('general', 'Request For Services'),
                    ('partnership', 'Partnership Queries'),
                    ('media', 'Media Queries'),
                    ('general queries', 'General Queries'),
                    ('feedback', 'Website Feedback'),
                    ('others', 'Others'),
                    )

    domain = models.CharField(max_length=100, null=True, blank=True)
    domain_url = models.URLField(max_length=200, null=True, blank=True)
    country = models.CharField(max_length=100)
    enquery_type = models.CharField(max_length=100, choices=ENQUERY_TYPES)

    # def __unicode__(self):
    #     return self.contact_info.full_name class BlogpostForm(forms.ModelForm):
    meta_description = forms.CharField(max_length=500, required=False)

    class Meta:
        model = Post
        exclude = ('tags', 'user', 'published_on', 'old_slugs') class BlogCategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        exclude = ('slug',)

    def __init__(self, *args, **kwargs):
        super(BlogCategoryForm, self).__init__(*args, **kwargs)

    def clean_max_published_blogs(self):
        if self.cleaned_data['max_published_blogs'] >= self.cleaned_data['min_published_blogs']:
            return self.cleaned_data['max_published_blogs']
        else:
            raise forms.ValidationError('Maximum No of blogposts should be greater than minimum') class CustomBlogSlugInlineFormSet(forms.BaseInlineFormSet):
    def clean(self):
        super(CustomBlogSlugInlineFormSet, self).clean()
        if any(self.errors):
            return
        active_slugs = 0
        for form in self.forms:
            if form.cleaned_data.get("is_active"):
                active_slugs += 1
        if active_slugs > 1:
            raise forms.ValidationError(
                "Only one slug can be active at a time.") class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=30, unique=True)
    email = models.EmailField(verbose_name='email address', max_length=255, unique=True, db_index=True,)
    user_roles = models.CharField(choices=USER_ROLES, max_length=10)
    is_employee = models.BooleanField(default=False)
    date_of_birth = models.DateField(default='1970-01-01')
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(_('staff status'), default=False)
    date_joined = models.DateTimeField(default=timezone.now)
    is_special = models.BooleanField(default=False)
    first_name = models.CharField(max_length=100, default='')
    last_name = models.CharField(max_length=100, default='')
    gender = models.CharField(choices=GENDER_TYPES, max_length=10)
    fb_profile = models.URLField(default='')
    tw_profile = models.URLField(default='')
    ln_profile = models.URLField(default='')
    google_plus_url = models.URLField(default='')
    about = models.CharField(max_length=2000, default='', null=True, blank=True)
    state = models.CharField(max_length=50)
    city = models.CharField(max_length=50)
    area = models.CharField(max_length=150)
    address = models.TextField(max_length=1000, default='')
    mobile = models.BigIntegerField(default='0')
    website = models.URLField(default='', null=True)
    phones = models.TextField(max_length=100, default='', null=True)
    pincode = models.TextField(max_length=50, default='', null=True)
    min_published_blogs = models.IntegerField(default=0)
    max_published_blogs = models.IntegerField(default=0)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    def get_full_name(self):
        # The user is identified by their email address
        return self.first_name + ' ' + self.last_name

    def get_short_name(self):
        # The user is identified by their email address
        return self.first_name

    def __unicode__(self):
        return self.first_name + ' (' + self.email + ')'

    def total_posts(self):
        return Post.objects.filter(user=self).count()

    def drafted_posts(self):
        return Post.objects.filter(user=self, status="D").count()

    def is_site_admin(self):
        if self.user_roles == "Admin" or self.is_superuser:
            return True
        return False

    class Meta:
        permissions = (
            ("blog_moderator", "Can enable or disable blog posts"),
            ("blogger", "Can write blog posts"),
        )

    def get_week_posts(self, value):
        if value:
            value = value.split('-')
            previous_date = datetime.strptime(value[0].strip(), "%Y/%m/%d").strftime("%Y-%m-%d")
            current_date = datetime.strptime(value[1].strip(), "%Y/%m/%d").strftime("%Y-%m-%d")
        else:
            current_date = datetime.strptime(str(datetime.now().date()), "%Y-%m-%d").strftime("%Y-%m-%d")
            previous_date = datetime.strptime(str(datetime.now().date() - timedelta(days=7)), "%Y-%m-%d").strftime("%Y-%m-%d")
        post = Post.objects.filter(user=self, created_on__range=(previous_date, current_date))
        return post.filter(status='P').count(), post.filter(status='D').count(), post.filter(status='R').count(), post.filter(status='T').count() class ContactForm(forms.ModelForm):
    email = forms.EmailField()
    full_name = forms.CharField(max_length=200)
    message = forms.CharField(max_length=200)
    country = forms.CharField(max_length=200, required=False)
    enquery_type = forms.CharField(max_length=200, required=False)

    class Meta:
        model = Contact
        exclude = ('full_name', 'message', 'email', 'phone', 'contact_info', 'country', 'enquery_type')

    def __init__(self, *args, **kwargs):
        super(ContactForm, self).__init__(*args, **kwargs)
        # if 'country' in self.data.keys():
        #     self.fields['country'].required = True

        if 'enquery_type' in self.data.keys():
            self.fields['enquery_type'].required = True class SubscribeForm(forms.ModelForm):
    class Meta:
        model = Subscribers
        fields = ('email',)

    def __init__(self, *args, **kwargs):
        super(SubscribeForm, self).__init__(*args, **kwargs)

    def clean_email(self):

        if str(self.data['is_blog']) == 'True':
            if len(self.data['is_category']) > 0:
                category = Category.objects.get(id=self.data['is_category'])
                existing_subscribers = Subscribers.objects.filter(email=self.data['email'], blog_post=True, category=category)
            else:
                existing_subscribers = Subscribers.objects.filter(email=self.data['email'], blog_post=True, category=None)
        else:
            existing_subscribers = Subscribers.objects.filter(email=self.data['email'], blog_post=False)
        if existing_subscribers:
            raise forms.ValidationError('User with email id is already Subscribed')

        return self.data['email']
from django.shortcuts import render_to_response, render, get_object_or_404, redirect
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.template.context_processors import csrf
from django.contrib.auth.decorators import login_required
from django.db.models import Prefetch
from micro_blog.models import Category, Tags, Post, Subscribers, Post_Slugs
from pages.models import Contact
from micro_blog.forms import BlogpostForm, BlogCategoryForm, CustomBlogSlugInlineFormSet
from django.forms.models import inlineformset_factory
from micro_admin.models import User
from pages.forms import ContactForm, SubscribeForm
from django.conf import settings
from microurl import google_mini
from django.core.urlresolvers import reverse
from django.template.defaultfilters import slugify
from .tasks import *
import math
import datetime
import json
import sendgrid
#     return render(request, 'admin/browse.html', {'files': imgs})

def empty(request):
    return render(request, 'site/empty.html')


@login_required
def admin_category_list(request):
    blog_categories = Category.objects.all().order_by('id')
    return render(request, 'admin/blog/blog-category-list.html', {'blog_categories': blog_categories})


@login_required
def new_blog_category(request):
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(request.POST)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category created'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category.html', {'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html')


@login_required
def edit_category(request, category_slug):
    blog_category = get_object_or_404(Category, slug=category_slug)
    if request.method == 'POST':
        validate_blogcategory = BlogCategoryForm(
            request.POST, instance=blog_category)
        if validate_blogcategory.is_valid():
            validate_blogcategory.save()

            # cache._cache.flush_all()
            data = {'error': False, 'response': 'Blog category updated'}
        else:
            data = {'error': True, 'response': validate_blogcategory.errors}
        return HttpResponse(json.dumps(data), content_type='application/json; charset=utf-8')

    if request.user.is_superuser:
        c = {}
        c.update(csrf(request))
        return render(request, 'admin/blog/blog-category-edit.html', {'blog_category': blog_category, 'csrf_token': c['csrf_token']})
    else:
        return render_to_response('admin/accessdenied.html')


@login_required
def delete_category(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if request.user.is_superuser:
        category.delete()

        # cache._cache.flush_all()
        return HttpResponseRedirect('/blog/category-list/')
    else:
        return render_to_response('admin/accessdenied.html')


@login_required
def change_category_status(request, category_slug):
    category = get_object_or_404(Category, slug=category_slug)
    if category.is_display:
        category.is_display = False
    else:
        category.is_display = True
    category.save()
    return HttpResponseRedirect('/blog/category-list/')


def get_prev_after_pages_count(page, no_pages):
    prev_page = page - 1
    if prev_page == 1:
        previous_page = prev_page
    else:
        previous_page = prev_page - 1
    if page == 1:
        prev_page = page
        previous_page = page

    if page == no_pages:
        aft_page = no_pages
        after_page = no_pages
    else:
        aft_page = page + 1
        if aft_page == no_pages:
            after_page = no_pages
        else:
            after_page = aft_page + 1
    return prev_page, previous_page, aft_page, after_page


def site_blog_home(request, **kwargs):
    page = 1
    if 'page' in request.GET.keys():
        try:
            if request.GET.get('page') and int(request.GET.get('page')):
                return redirect(reverse('site_blog_home', kwargs={'page_num': request.GET.get('page')}))
        except:
            return redirect(reverse('site_blog_home'))
    if 'page_num' in kwargs:
        try:
            page = int(kwargs['page_num'])
            if page == 1:
                return redirect(reverse('site_blog_home'))
        except:
            return redirect(reverse('site_blog_home'))
    items_per_page = 10

    posts = Post.objects.filter(status='P').order_by(
        '-published_on').select_related("user").prefetch_related(

        Prefetch("slugs", queryset=Post_Slugs.objects.filter(is_active=True),