import json
from django.shortcuts import redirect, render
from django.core.paginator import Paginator
import requests

from bigsansar.contrib.sites.models import domains, pages

# Create your views here.


def manage_domain(request, id):
    if request.user.is_authenticated:

        try:
            ruser = request.user
            query = domains.objects.get(id=id, user=ruser)

        except:

            return render(request, '404.html')

        else:
            status = query.visitor
            if status == 0:
                visitor = 'Deactive'

            else:
                visitor = 'Active'

            getpage = pages.objects.filter(domain=id).order_by('-id')
            paginator = Paginator(getpage, 5)
            page_number = request.GET.get('page')
            page = paginator.get_page(page_number)
            ip = request.META.get('REMOTE_ADDR')
            res = requests.get('http://ip-api.com/json/' + ip)
            location_data_one = res.text
            geo = json.loads(location_data_one)
            browser = request.META['HTTP_USER_AGENT']
            update = None
            #admin_update.objects.all().order_by('-id')[:5]
            return render(request, 'admin/domain_manage.html', {'visitcount': status, 'count': visitor, 'host': query,
                                                          'pages': page, 'ip': ip, 'geo': geo, 'browser': browser,
                                                          'blog': update})
    else:
        return redirect('/admin')
