from django.shortcuts import render
from django.http import JsonResponse, HttpResponse
# Create your views here.
from cms.models import Django_cms,Science_applied
from StratFit import settings
from rest_framework.decorators import api_view, authentication_classes
from django.views.decorators.cache import never_cache
try: # for pip >= 10
    from pip._internal.req.req_install import logger
except ImportError: # for pip <= 9.0.3
    from pip.req.req_install import logger
from Subscriber.Authentication import StartFitAuthentication,SessionAuthentication,StartFitSessionUtil, AuthResponse,IsAuthenticated
from Subscriber.models import User   
import json
from django.forms import model_to_dict
@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache                
def Blog_content(request):
    stratsessionutil = StartFitSessionUtil()
    json_content=json.loads(request.body.decode('utf-8'))
    CMS_Id=[]
    try:
        username = stratsessionutil.get_user_insession(request)
        user = username['id']
        if username != None: 
            
            if 'id' in json_content and json_content['id']!= '' and json_content['id']!= 'null' and json_content['id']!=None:
                content_id=json_content['id']
                CMS=Django_cms.objects.filter(id=content_id).values()
                if CMS.exists():
                    cms=Django_cms.objects.get(id=content_id)
                    if 'content' in json_content and json_content['content']!='' and json_content['content']!='null' and json_content['content']!=None: 
                        cms.content=json_content['content']
                        cms.save()
                    if 'title' in json_content and json_content['title']!='' and json_content['title']!='null' and json_content['title']!=None:
                        cms.title=json_content['title']
                        cms.save()

                    return JsonResponse({"success":True,"message":"Blog updated successfully"}) 
            else:
                if 'id' not in json_content:
                    CMS=Django_cms.objects.filter(title=json_content['title']).values()
                    if CMS.exists():
                        
                        cms=Django_cms.objects.get(title=json_content['title'])
                        if 'content' in json_content and json_content['content']!='' and json_content['content']!='null' and json_content['content']!=None: 
                            cms.content=json_content['content']
                            cms.save()
                        if 'title' in json_content and json_content['title']!='' and json_content['title']!='null' and json_content['title']!=None:
                            cms.title=json_content['title']
                            cms.save()
                        return JsonResponse({"success":True,"message":"updated successfully"})    
                    else:

                        cms=Django_cms.objects.create(content=json_content['content'],
                        title=json_content['title'],
                        createdBy_id=user,modified_By_id=user)
                        cms.save()
                        CMS_Id=cms.id

                        return JsonResponse({"success":True,"cms_id":CMS_Id,"message":"Blog stored successfully"})    
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})
    
@api_view(['GET', 'POST'])
@never_cache                
def getBlog_content(request):
    info=json.loads(request.body.decode('utf-8'))
    Blog={}
    try:
        
        array=[]
        
        if 'id' in info and info['id']!=''  and info['id']!='null'and info['id']!=None:
            cms_content=Django_cms.objects.filter(id=info['id']).values()
            if cms_content.exists():
                content=cms_content[0]['content']
                Blog['content']=content
                return JsonResponse({"success":True,"Blog":Blog})
        else:
            #cms=Django_cms.objects.all()
            ghghg=Django_cms.objects.all().order_by('-id')
            hg=ghghg
            for dt in hg:
                j=model_to_dict(dt)
                print(j)
                array.append(j)
            return JsonResponse({"success":True,"Blogs":array})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})        


@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache                
def deleteBlog_content(request):
    stratsessionutil = StartFitSessionUtil()
    info=json.loads(request.body.decode('utf-8'))
    Blog={}
    try:
        username = stratsessionutil.get_user_insession(request)
        user=username['id']
        print(user)
        array=[]
        if username!=None:
            if 'title' in info and info['title']!=''  and info['title']!='null'and info['title']!=None:
                cms_content=Django_cms.objects.filter(title=info['title']).delete()
                
                return JsonResponse({"success":True,"message":"successfully deleted"})
            else:
                return JsonResponse({"success":False,"message":"please provide the title"})    
        else:
            return JsonResponse({"success":False,"message":"user logged out"})
    except Exception as e:
        logger.exception("something wrong")
        return JsonResponse({"msg": str(e)})        
 
@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def Science_link(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        info = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            if 'id' in info and info['id']!= None:
                blog=Science_applied.objects.filter(id=info['id'])
                if blog.exists():
                    Blog=Science_applied.objects.get(id=info['id'])
                    if 'title' in info and info['title']!= None:
                        Blog.science_title=info['title']
                    if 'link' in info and info['link']!= None:
                        Blog.link=info['link']
                    if 'status' in info and info['status']!=None:
                        Blog.status=info['status']
                    Blog.save()    
                return JsonResponse({"success":True,"message":"Blog link saved successfully"})        
            else:
                array=[]
                science={}
                Blog=Science_applied.objects.filter(science_title=info['title'],status=1)
                if Blog.exists():
                    return JsonResponse({"success":True,"message":"title already exists please give the id"})
                else:
                    Blog=Science_applied.objects.create(science_title=info['title'],link=info['link'],status=1,createdBy_id=user,modified_By_id=user)
                    Blog.save()
                    link=model_to_dict(Blog)
                    print(link['status'])
                    science['id']=link['id']
                    science['title']=link['science_title']
                    science['link']=link['link']
                    science['status']=link['status']
                    array.append(science)
                       
                    return JsonResponse({"success":True,"message":"Blog link successfully saved","link_info":array})   

        else:
            return JsonResponse({"success":False,"message":"user logged out"})

    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False})  

@api_view(['GET', 'POST'])
@authentication_classes((SessionAuthentication, IsAuthenticated))
@never_cache
def removelink(request):
    stratsessionutil = StartFitSessionUtil()
    try:
        username = stratsessionutil.get_user_insession(request)
        info = json.loads(request.body.decode('utf-8'))
        user = username['id']
        if username != None:
            if 'id' in info and info['id']!= None:
                blog=Science_applied.objects.filter(id=info['id']).update(status=0)
                if blog:
                    return JsonResponse({"success":True,"message":"link deleted successfully"})
                else:
                    return JsonResponse({"success":False,"message":"enter valid id"})    
            else:
                return JsonResponse({"success":False,"message":"enter the id"})    
        else:
            return JsonResponse({"success":False,"message":"user logged out"})

    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False}) 

@api_view(['GET', 'POST'])
@never_cache
def Sciencelinks(request):
    try:
        info = json.loads(request.body.decode('utf-8'))
        array=[]
        list={}
        link=Science_applied.objects.filter(status=1)
        for dt in link:
            blog=model_to_dict(dt)
            list['id']=blog['id']
            list['science_title']=blog['science_title']
            list['link']= blog['link']
            list['status']= blog['status']
            array.append(list)
            list={}
        return JsonResponse({"success":True,"message":array})                       
    except Exception as e:
        logger.error("error")
        return JsonResponse({"msg": str(e),"success":False})  




