from django.conf import settings
from django.core import serializers
from django.utils import timezone
import requests
from Posts.commentModel import Comments
#from Posts.commentView import add_Comment
from rest_framework import status
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.response import Response
from django.shortcuts import HttpResponse, render
from requests import get
from .serializers import CommentSerializer, PostSerializer
from Author.serializers import LikeSerializer
from Author.models import Like
from Author.views import updateForeignAuthors, GetForeignAuthors
from .models import Post, Author
from .form import PostForm
from Posts.commentForm import CommentForm
import json
import uuid
import re
import base64
from django.db.models import Q
import django.core
from permissions import CustomAuthentication, AccessPermission
from django.core.paginator import Paginator
import traceback

def newPost(request, uid=None, auth_pk=None):
    form = PostForm(request.POST, request.FILES)
    if form.is_valid():
        title = form.cleaned_data['title']
        descirption = form.cleaned_data['description']
        categories = form.cleaned_data['categories'].split(' ')
        visibility = form.cleaned_data['visibility']
        unlisted = form.cleaned_data['unlisted']
        contentType = form.cleaned_data['contentType']

        if contentType == "application/app": 
            content = request.FILES['file'].read() #Inputfile
        elif contentType in ["image/png", "image/jpeg",]:
            content = base64.b64encode(request.FILES['file'].read()) #Inputfile
        else:
            content = form.cleaned_data["text"]

        source = settings.SERVER_URL + "/"
        origin = settings.SERVER_URL + "/"

        author_id = Author.objects.get(pk=auth_pk)
        id = author_id.url
        author = json.loads(serializers.serialize('json', Author.objects.filter(pk=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields']

        if uid == None:
            r_uid = uuid.uuid4().hex
            uid = re.sub('-', '', r_uid)
        id = id + '/posts/' + uid + "/"
        comments_id = id + "comments/"

        published = timezone.now()

        posts = Post(pk=uid, id=id, author_id=author_id, author=author, title=title, source=source, origin=origin, description=descirption, contentType=contentType, count=0, size=10, categories=categories,visibility=visibility, unlisted=unlisted, published=published, content=content, comments=comments_id)
        posts.save()
        return True
    else:
        print(request.data)
        print(form.errors)
        print(form.data)
        return False

def add_Comment(request, post_pk, auth_pk, uid=None):
    form = CommentForm(request.POST, request.FILES)
    if form.is_valid():
        updateForeignAuthors()
        published = timezone.now()
        contentType = form.cleaned_data['contentType']
        if contentType == "application/app": 
            content = request.FILES['file'].read() #Inputfile
        elif contentType in ["image/png", "image/jpeg",]:
            content = base64.b64encode(request.FILES['file'].read()) #Inputfile
        else:
            content = form.cleaned_data["text"]
              
        author_id = json.loads(serializers.serialize('json', Author.objects.filter(email=auth_pk), fields=('type', 'id', 'host', 'displayName', 'url', 'github',)))[0]['fields']

        post = Post.objects.get(pk = post_pk)
        post_pk_str = post_pk
        if uid == None:
            r_uid = uuid.uuid4().hex
            uid = re.sub('-', '', r_uid)
        comment_id = getattr(post, 'comments') + uid
        comments = Comments(pk=uid, id=comment_id, Post_pk=post, Post_pk_str = post_pk_str, auth_pk_str = auth_pk, author=author_id, size=10, published=published, contentType=contentType, content=content)
        comments.save()
        return True
    else:
        print(request.data)   
        return False
        
@api_view(['GET',])
@authentication_classes([CustomAuthentication])
@permission_classes([AccessPermission])
def PostLikesView(request, post_pk, auth_pk):
    post = Post.objects.get(post_pk = post_pk)
    author = Author.objects.get(pk = auth_pk)
    likeObjs = Like.objects.filter(~Q(auth_pk = author), object = post.id)

    Likes = LikeSerializer(likeObjs, read_only=True, many=True)
    likes = []
    for l in Likes.data:
        like = {}
        for key in l:
            if(key != "context"):
                like[key] = l[key]
        like["@context"] = l["context"]
        like["author"] = json.loads(django.core.serializers.serialize('json', Author.objects.filter(id=l["author"]), fields=('type', 'id', 'displayName', 'host', 'url', 'github',)))[0]['fields']
        likes.append(like)

    
    response_dict = {
        "type": "likes",
        "items": likes
    }
    return Response(response_dict)


@api_view(['GET', 'POST',])
@authentication_classes([CustomAuthentication])
@permission_classes([AccessPermission])
def PostsList(request, auth_pk=None):
    page_number = request.GET.get('page')
    if 'size' in request.GET:
        page_size = request.GET.get('size')
    else:
        page_size = 5

    if request.method == 'GET':
        if auth_pk:
            try:
                author = Author.objects.get(auth_pk=auth_pk)
                posts = Post.objects.filter(author_id=author, id__icontains = "linkedspace")
                code = status.HTTP_200_OK
                paginator = Paginator(posts, page_size)
                page_obj = paginator.get_page(page_number)
                data = PostSerializer(page_obj.object_list, many=True).data
            except Exception as e:
                print(e)
                data = {}
                code = status.HTTP_400_BAD_REQUEST
        else:
            code = status.HTTP_200_OK
            posts = Post.objects.filter(id__icontains = "linkedspace")
            paginator = Paginator(posts, page_size)
            page_obj = paginator.get_page(page_number)
            data = PostSerializer(page_obj.object_list, many=True).data

    elif request.method == 'POST':
        if newPost(request, auth_pk=request.data['auth_pk']):
            code = status.HTTP_201_CREATED
            post = Post.objects.latest("published")
            data = PostSerializer(post).data
        else:
            code = status.HTTP_400_BAD_REQUEST
            data = {}

    return Response(data, code)

@api_view(['GET', 'POST',])
@authentication_classes([CustomAuthentication])
@permission_classes([AccessPermission])
def commentListView(request, post_pk, auth_pk=None):
    page_number = request.GET.get('page')
    if 'size' in request.GET:
        page_size = request.GET.get('size')
    else:
        page_size = 5
        
    if request.method == 'GET':
        comments = Comments.objects.filter(Post_pk_str=post_pk)
        post = Post.objects.get(pk=post_pk)
        post_id = getattr(post, 'id')
        comment_id = getattr(post, 'comments')
        paginator = Paginator(comments, page_size)
        page_obj = paginator.get_page(page_number)
        serializer = CommentSerializer(page_obj.object_list, many=True)
        
        response_dict = {
            "type": "comments",
            "page": page_number,
            "size": page_size,
            "post": post_id,
            "id": comment_id,
            "comments": serializer.data,
        }
        
        return Response(response_dict)
        
    elif request.method == 'POST':
        if add_Comment(request, post_pk=request.data['Post_pk'], auth_pk=request.data['auth_pk']):
            code = status.HTTP_202_ACCEPTED
            comment = Comments.objects.latest("published")
            data = CommentSerializer(comment).data
        else:
            code = status.HTTP_400_BAD_REQUEST
            data = {}
        
        return Response(data, code)

@api_view(['GET', 'POST', 'PUT', 'DELETE', ])
@authentication_classes([CustomAuthentication])
@permission_classes([AccessPermission])
def PostDetail(request, post_pk, auth_pk=None):
    page_number = request.GET.get('page')
    if 'size' in request.GET:
        page_size = request.GET.get('size')
    else:
        page_size = 5

    if request.method == 'GET':
        try:
            code = status.HTTP_200_OK
            post = Post.objects.get(post_pk=post_pk)
            serializer = PostSerializer(post)
        except Exception as e:
            print(e)
            code = status.HTTP_404_NOT_FOUND

            post = Post.objects.all()
            paginator = Paginator(post, page_size)
            page_obj = paginator.get_page(page_number)
            serializer = PostSerializer(page_obj.object_list, many=True)

    elif request.method == 'POST':
        try:
            code = status.HTTP_200_OK
            post = Post.objects.get(post_pk=post_pk)
            if 'title' in request.data.keys():
                post.title = request.data['title']
            if 'description' in request.data.keys():
                post.description = request.data['description']
            if 'categories' in request.data.keys():
                post.categories = request.data['categories'].split(' ')
            if 'visibility' in request.data.keys():
                post.visibility = request.data['visibility']
            if 'unlisted' in request.data.keys():
                post.unlisted = request.data['unlisted']
            if 'contentType' in request.data.keys():
                post.contentType = request.data['contentType']

                if post.contentType == "application/app":
                     post.content = request.FILES['file'].read() #Inputfile
                elif post.contentType in ["image/png", "image/jpeg",]:
                     post.content = base64.b64encode(request.FILES['file'].read()) #Inputfile
                else:
                    post.content = request.data["text"]

            post.save()
            serializer = PostSerializer(post)
        except Exception as e:
            print(e)
            code = status.HTTP_400_BAD_REQUEST

            post = Post.objects.all()
            paginator = Paginator(post, page_size)
            page_obj = paginator.get_page(page_number)
            serializer = PostSerializer(page_obj.object_list, many=True)

    elif request.method == 'PUT':
        try:
            code = status.HTTP_201_CREATED
            assert newPost(request, post_pk, request.data['auth_pk'])==True
            post = Post.objects.get(post_pk=post_pk)
            serializer = PostSerializer(post)
        except Exception as e:
            print(e)
            code = status.HTTP_400_BAD_REQUEST

            post = Post.objects.all()
            paginator = Paginator(post, page_size)
            page_obj = paginator.get_page(page_number)
            serializer = PostSerializer(page_obj.object_list, many=True)

    elif request.method == 'DELETE':
        try:
            post = Post.objects.get(post_pk=post_pk)
            post.delete()
            code = status.HTTP_200_OK
        except Exception as e:
            print(e)
            code = status.HTTP_404_NOT_FOUND

        post = Post.objects.all()
        paginator = Paginator(post, page_size)
        page_obj = paginator.get_page(page_number)
        serializer = PostSerializer(page_obj.object_list, many=True)

    return Response(serializer.data, code)

@api_view(['GET', 'POST', ])
@authentication_classes([CustomAuthentication])
@permission_classes([AccessPermission])
def commentDetail(request, post_pk, comment_pk, auth_pk=None):
    page_number = request.GET.get('page')
    if 'size' in request.GET:
        page_size = request.GET.get('size')
    else:
        page_size = 5
        
    if request.method == 'GET':
        try:
            code = status.HTTP_200_OK
            comment = Comments.objects.get(pk=comment_pk)
            serializer = CommentSerializer(comment)
        except Exception as e:
            print(e)
            code = status.HTTP_404_NOT_FOUND

            comment = Comments.objects.all()
            paginator = Paginator(comment, page_size)
            page_obj = paginator.get_page(page_number)
            serializer = CommentSerializer(page_obj.object_list, many=True)

    elif request.method == 'POST':
        try:
            code = status.HTTP_200_OK
            comment = Comments.objects.get(pk=comment_pk)
            if 'contentType' in request.data.keys():
                comment.contentType = request.data['contentType']
            if 'text' in request.data.keys():
                comment.content = request.data['text']
            comment.save()
            serializer = CommentSerializer(comment)
        except Exception as e:
            print(e)
            code = status.HTTP_400_BAD_REQUEST
            comment = Comments.objects.all()
            paginator = Paginator(comment, page_size)
            page_obj = paginator.get_page(page_number)
            serializer = CommentSerializer(page_obj.object_list, many=True)
            
    return Response(serializer.data, code)
            
            
@api_view(['GET',])
def connection(request, auth_id=None):
    data = []

    team3 = get('https://social-dis.herokuapp.com/posts', auth=('socialdistribution_t03','c404t03'))
    if team3.status_code == 200:
        data.append(team3.json())

    team15 = get('https://unhindled.herokuapp.com/service/allposts/', auth=('connectionsuperuser','404connection'))
    if team15.status_code == 200:
        data.append(team15.json())

    team17 = get('https://cmput404f21t17.herokuapp.com/service/connect/public/', auth=('4cbe2def-feaa-4bb7-bce5-09490ebfd71a','123456'))
    if team17.status_code == 200:
        data.append(team17.json())

    return Response({'connection': data})


[((98, 1, 98, 19), 'rest_framework.decorators.api_view', 'api_view', ({(98, 10, 98, 18): "['GET']"}, {}), "(['GET'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((99, 1, 99, 47), 'rest_framework.decorators.authentication_classes', 'authentication_classes', ({(99, 24, 99, 46): '[CustomAuthentication]'}, {}), '([CustomAuthentication])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((100, 1, 100, 39), 'rest_framework.decorators.permission_classes', 'permission_classes', ({(100, 20, 100, 38): '[AccessPermission]'}, {}), '([AccessPermission])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((125, 1, 125, 27), 'rest_framework.decorators.api_view', 'api_view', ({(125, 10, 125, 26): "['GET', 'POST']"}, {}), "(['GET', 'POST'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((126, 1, 126, 47), 'rest_framework.decorators.authentication_classes', 'authentication_classes', ({(126, 24, 126, 46): '[CustomAuthentication]'}, {}), '([CustomAuthentication])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((127, 1, 127, 39), 'rest_framework.decorators.permission_classes', 'permission_classes', ({(127, 20, 127, 38): '[AccessPermission]'}, {}), '([AccessPermission])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((166, 1, 166, 27), 'rest_framework.decorators.api_view', 'api_view', ({(166, 10, 166, 26): "['GET', 'POST']"}, {}), "(['GET', 'POST'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((167, 1, 167, 47), 'rest_framework.decorators.authentication_classes', 'authentication_classes', ({(167, 24, 167, 46): '[CustomAuthentication]'}, {}), '([CustomAuthentication])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((168, 1, 168, 39), 'rest_framework.decorators.permission_classes', 'permission_classes', ({(168, 20, 168, 38): '[AccessPermission]'}, {}), '([AccessPermission])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((207, 1, 207, 45), 'rest_framework.decorators.api_view', 'api_view', ({(207, 10, 207, 44): "['GET', 'POST', 'PUT', 'DELETE']"}, {}), "(['GET', 'POST', 'PUT', 'DELETE'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((208, 1, 208, 47), 'rest_framework.decorators.authentication_classes', 'authentication_classes', ({(208, 24, 208, 46): '[CustomAuthentication]'}, {}), '([CustomAuthentication])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((209, 1, 209, 39), 'rest_framework.decorators.permission_classes', 'permission_classes', ({(209, 20, 209, 38): '[AccessPermission]'}, {}), '([AccessPermission])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((297, 1, 297, 28), 'rest_framework.decorators.api_view', 'api_view', ({(297, 10, 297, 27): "['GET', 'POST']"}, {}), "(['GET', 'POST'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((298, 1, 298, 47), 'rest_framework.decorators.authentication_classes', 'authentication_classes', ({(298, 24, 298, 46): '[CustomAuthentication]'}, {}), '([CustomAuthentication])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((299, 1, 299, 39), 'rest_framework.decorators.permission_classes', 'permission_classes', ({(299, 20, 299, 38): '[AccessPermission]'}, {}), '([AccessPermission])', False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((342, 1, 342, 19), 'rest_framework.decorators.api_view', 'api_view', ({(342, 10, 342, 18): "['GET']"}, {}), "(['GET'])", False, 'from rest_framework.decorators import api_view, authentication_classes, permission_classes\n'), ((71, 11, 71, 51), 'Posts.commentForm.CommentForm', 'CommentForm', ({(71, 23, 71, 35): 'request.POST', (71, 37, 71, 50): 'request.FILES'}, {}), '(request.POST, request.FILES)', False, 'from Posts.commentForm import CommentForm\n'), ((106, 12, 106, 63), 'Author.serializers.LikeSerializer', 'LikeSerializer', (), '', False, 'from Author.serializers import LikeSerializer\n'), ((122, 11, 122, 34), 'rest_framework.response.Response', 'Response', ({(122, 20, 122, 33): 'response_dict'}, {}), '(response_dict)', False, 'from rest_framework.response import Response\n'), ((164, 11, 164, 31), 'rest_framework.response.Response', 'Response', ({(164, 20, 164, 24): 'data', (164, 26, 164, 30): 'code'}, {}), '(data, code)', False, 'from rest_framework.response import Response\n'), ((295, 11, 295, 42), 'rest_framework.response.Response', 'Response', ({(295, 20, 295, 35): 'serializer.data', (295, 37, 295, 41): 'code'}, {}), '(serializer.data, code)', False, 'from rest_framework.response import Response\n'), ((339, 11, 339, 42), 'rest_framework.response.Response', 'Response', ({(339, 20, 339, 35): 'serializer.data', (339, 37, 339, 41): 'code'}, {}), '(serializer.data, code)', False, 'from rest_framework.response import Response\n'), ((346, 12, 346, 100), 'requests.get', 'get', (), '', False, 'from requests import get\n'), ((350, 13, 350, 115), 'requests.get', 'get', (), '', False, 'from requests import get\n'), ((354, 13, 354, 136), 'requests.get', 'get', (), '', False, 'from requests import get\n'), ((358, 11, 358, 41), 'rest_framework.response.Response', 'Response', ({(358, 20, 358, 40): "{'connection': data}"}, {}), "({'connection': data})", False, 'from rest_framework.response import Response\n'), ((59, 20, 59, 34), 'django.utils.timezone.now', 'timezone.now', ({}, {}), '()', False, 'from django.utils import timezone\n'), ((73, 8, 73, 30), 'Author.views.updateForeignAuthors', 'updateForeignAuthors', ({}, {}), '()', False, 'from Author.views import updateForeignAuthors, GetForeignAuthors\n'), ((74, 20, 74, 34), 'django.utils.timezone.now', 'timezone.now', ({}, {}), '()', False, 'from django.utils import timezone\n'), ((91, 19, 91, 204), 'Posts.commentModel.Comments', 'Comments', (), '', False, 'from Posts.commentModel import Comments\n'), ((177, 19, 177, 63), 'Posts.commentModel.Comments.objects.filter', 'Comments.objects.filter', (), '', False, 'from Posts.commentModel import Comments\n'), ((181, 20, 181, 50), 'django.core.paginator.Paginator', 'Paginator', ({(181, 30, 181, 38): 'comments', (181, 40, 181, 49): 'page_size'}, {}), '(comments, page_size)', False, 'from django.core.paginator import Paginator\n'), ((194, 15, 194, 38), 'rest_framework.response.Response', 'Response', ({(194, 24, 194, 37): 'response_dict'}, {}), '(response_dict)', False, 'from rest_framework.response import Response\n'), ((55, 18, 55, 40), 're.sub', 're.sub', ({(55, 25, 55, 28): '"""-"""', (55, 30, 55, 32): '""""""', (55, 34, 55, 39): 'r_uid'}, {}), "('-', '', r_uid)", False, 'import re\n'), ((89, 18, 89, 40), 're.sub', 're.sub', ({(89, 25, 89, 28): '"""-"""', (89, 30, 89, 32): '""""""', (89, 34, 89, 39): 'r_uid'}, {}), "('-', '', r_uid)", False, 'import re\n'), ((104, 36, 104, 55), 'django.db.models.Q', 'Q', (), '', False, 'from django.db.models import Q\n'), ((151, 24, 151, 51), 'django.core.paginator.Paginator', 'Paginator', ({(151, 34, 151, 39): 'posts', (151, 41, 151, 50): 'page_size'}, {}), '(posts, page_size)', False, 'from django.core.paginator import Paginator\n'), ((205, 15, 205, 35), 'rest_framework.response.Response', 'Response', ({(205, 24, 205, 28): 'data', (205, 30, 205, 34): 'code'}, {}), '(data, code)', False, 'from rest_framework.response import Response\n'), ((310, 22, 310, 57), 'Posts.commentModel.Comments.objects.get', 'Comments.objects.get', (), '', False, 'from Posts.commentModel import Comments\n'), ((54, 20, 54, 32), 'uuid.uuid4', 'uuid.uuid4', ({}, {}), '()', False, 'import uuid\n'), ((88, 20, 88, 32), 'uuid.uuid4', 'uuid.uuid4', ({}, {}), '()', False, 'import uuid\n'), ((141, 28, 141, 55), 'django.core.paginator.Paginator', 'Paginator', ({(141, 38, 141, 43): 'posts', (141, 45, 141, 54): 'page_size'}, {}), '(posts, page_size)', False, 'from django.core.paginator import Paginator\n'), ((199, 22, 199, 58), 'Posts.commentModel.Comments.objects.latest', 'Comments.objects.latest', ({(199, 46, 199, 57): '"""published"""'}, {}), "('published')", False, 'from Posts.commentModel import Comments\n'), ((227, 24, 227, 50), 'django.core.paginator.Paginator', 'Paginator', ({(227, 34, 227, 38): 'post', (227, 40, 227, 49): 'page_size'}, {}), '(post, page_size)', False, 'from django.core.paginator import Paginator\n'), ((316, 22, 316, 44), 'Posts.commentModel.Comments.objects.all', 'Comments.objects.all', ({}, {}), '()', False, 'from Posts.commentModel import Comments\n'), ((317, 24, 317, 53), 'django.core.paginator.Paginator', 'Paginator', ({(317, 34, 317, 41): 'comment', (317, 43, 317, 52): 'page_size'}, {}), '(comment, page_size)', False, 'from django.core.paginator import Paginator\n'), ((324, 22, 324, 57), 'Posts.commentModel.Comments.objects.get', 'Comments.objects.get', (), '', False, 'from Posts.commentModel import Comments\n'), ((262, 24, 262, 50), 'django.core.paginator.Paginator', 'Paginator', ({(262, 34, 262, 38): 'post', (262, 40, 262, 49): 'page_size'}, {}), '(post, page_size)', False, 'from django.core.paginator import Paginator\n'), ((291, 20, 291, 46), 'django.core.paginator.Paginator', 'Paginator', ({(291, 30, 291, 34): 'post', (291, 36, 291, 45): 'page_size'}, {}), '(post, page_size)', False, 'from django.core.paginator import Paginator\n'), ((334, 22, 334, 44), 'Posts.commentModel.Comments.objects.all', 'Comments.objects.all', ({}, {}), '()', False, 'from Posts.commentModel import Comments\n'), ((335, 24, 335, 53), 'django.core.paginator.Paginator', 'Paginator', ({(335, 34, 335, 41): 'comment', (335, 43, 335, 52): 'page_size'}, {}), '(comment, page_size)', False, 'from django.core.paginator import Paginator\n'), ((277, 24, 277, 50), 'django.core.paginator.Paginator', 'Paginator', ({(277, 34, 277, 38): 'post', (277, 40, 277, 49): 'page_size'}, {}), '(post, page_size)', False, 'from django.core.paginator import Paginator\n')]