from userapp.models import *
from rest_framework.permissions import AllowAny
from django.contrib.auth.models import User
from rest_framework.views import APIView
from django.http import JsonResponse
from django.shortcuts import render
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from django.views.generic.base import TemplateView
from userapp.serializers.userapp_serializer import *
import json
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from rest_framework import status
from django.http import HttpResponse,HttpResponseRedirect
from django.conf import settings
import csv , os
from PIL import Image

class UserAppLogin(APIView):
	'''
	For the  login operations of the userinfo master 
	'''
	permission_classes = (AllowAny,)

	def post(self, request):
		user_info_data = []
		try:
			user = authenticate(username=request.POST['username'], password=request.POST['password']) 
			if user is not None:
				if user.is_superuser == True :
					message ,code,status = 'Admin cannot login.',200,'success'
				else: 
					user_info = UserInfo.objects.filter(user_id_id=user.id).first()
					if user_info:
						token ,status = Token.objects.get_or_create(user=user)
						user_info_data = UserInfoSerializer(user_info)
						user_info_data = user_info_data.data
						message ,code,status = 'Login Successful',200,'success' 
					else:
						message ,code,status = 'User Credentials were incorrect',200,'success'				
			else:
				message ,code,status = 'User Credentials were incorrect',200,'success'
		except Exception as error:
			message ,code, status = 'Something went wrong:' +str(error), 500,'error'
		try:
			if token:
				token = token.key
		except Exception as e:
			token =''
		return JsonResponse({'message': message ,'status' : status , 'code' : code ,'token' : token, 'info' : user_info_data})



class UserAppLogout(APIView):
    def get(self, request, format=None):
        # simply delete the token to force a login
        request.user.auth_token.delete()
        return Response(status=status.HTTP_200_OK)


class UserPosts(APIView):
	'''
	For the job operations of the users posts 
	'''
	def get(self,request):
		user_info_data = {}
		try:
			user_id = request.user.id
			if user_id:
				user_info_data = {}
				user_post = UserAddedPost.objects.filter(userinfo_id__user_id_id=int(user_id)).order_by('-id')
				if user_post:
					user_posts_serializer = UserPostSerializer(user_post, many=True) 
					user_info_data = user_posts_serializer.data
					message ,code ,status = 'Fetched successfully.','success' ,200 
				else:
					message ,code,status = 'No post data.',200,'success'
			else:
				message ,code,status = 'Invalid User.',200,'success'
		except Exception as e:
			message ,code,status = 'Something went wrong :' +str(e) ,500,'error'

		return JsonResponse({'message': message ,'status' : status , 'code' : code ,'info' : user_info_data})

	def post(self,request):
		try:
			user_id = request.user.id
			if user_id:
				image = request.FILES.get('image')
				target_users = request.POST.get('target_users')
				keyboard_id = request.POST.get('keyboard_id')
				if 'image' not in request.FILES:
					return JsonResponse({'message': 'Please enter the image.','status' : 'success' , 'code' : 200 })
				if 'target_users' not in request.POST:
					return JsonResponse({'message': 'Please enter the target_users','status' : 'success' , 'code' : 200 })
				else:
					if request.POST['target_users'] == None or request.POST['target_users'] == '':
						return JsonResponse({'message': 'Enter the value for the  target_users','status' : 'success' , 'code' : 200 })
				if 'keyboard_id' not in request.POST:
					return JsonResponse({'message': 'Please enter the keyboard_id','status' : 'success' , 'code' : 200 })
				else:
					if request.POST['keyboard_id'] == None or request.POST['keyboard_id'] == '':
						return JsonResponse({'message': 'Enter the value for the keyboard_id','status' : 'success' , 'code' : 200 })

				obj = UserInfo.objects.filter(user_id_id=int(user_id)).first()
				if obj:
					if int(obj.coins) < (int(target_users) * 2):
						return JsonResponse({'message': 'User has '+ str(obj.coins)+' coins. It requires min '+ str(int(target_users) * 2) +' coins for this target users.','status' : 'success' , 'code' : 200 })
					else:
						obj.coins = int(obj.coins) - (int(target_users) * 2)						
						try:
							userinfo_id = UserInfo.objects.filter(user_id_id=int(user_id)).first()
							if userinfo_id:
								post_owner_id = userinfo_id.id
								save_obj = UserAddedPost.objects.create(userinfo_id_id=int(post_owner_id),image=image,keyboard_id_id=int(keyboard_id),post_view_access=target_users,total_view=target_users)
								obj.save()
								image_name = save_obj.image.name
								file = os.path.join(settings.MEDIA_ROOT+'/'+image_name)
								im = Image.open(file)
								im.thumbnail((100,100))
								name = '100X100_' + str(image_name)
								thumb_file = os.path.join(settings.MEDIA_ROOT+'/'+name)
								im.save(thumb_file)
								message ,code,status = 'Post has been added successfully.', 200 , 'success'
							else:
								message ,code,status = 'Invalid User.',200, 'success'
						except Exception as e:
							message ,code,status = 'Something went wrong :' +str(e) ,500, 'error'
				else:
					message ,code,status = 'Invalid User.',200,'success'
			else:
				message ,code,status = 'Invalid User.',200,'success'
		except Exception as e:
			message ,code,status = 'Something went wrong :' +str(e) ,500,'error'

		return JsonResponse({'message': message ,'status' : status , 'code' : code })

	def delete(self,request):
		try:
			user_id = request.user.id
			if user_id:
				if 'post_id' not in request.POST:
					return JsonResponse({'message':'post_id is missing.','status': 'success','code':200 })
				else:
					post_id = request.POST.get('post_id')
					to_be_deleted = UserAddedPost.objects.filter(id=int(post_id)).first()
					if to_be_deleted:
						to_be_deleted.delete()
						message ,code,status = 'Post deleted successfully.',200,'success'
					else:
						message ,code,status = 'Invalid post_id.',200,'success'
			else:
				message ,code,status = 'Invalid User.',200,'success'
		except Exception as e:
			message ,code,status = 'Something went wrong :' +str(e) ,500,'error'

		return JsonResponse({'message': message ,'status' : status , 'code' : code })



class UserPostsCSV(APIView):
	'''
	For the perations of the users posts csv  
	'''
	def get(self,request):
		try:
			user_id = request.user.id
			if user_id:
				obj = UserAddedPost.objects.filter(userinfo_id__user_id_id=int(user_id)).order_by('-id')
				if obj:
					response = HttpResponse(content_type='text/csv')
					response['Content-Disposition'] = 'attachment; filename="post_report.csv"'
					writer = csv.writer(response)
					c=1
					writer.writerow(['S.No','Post Link','View Limit','Current Views','Is_offensive'])      
					for i in obj:
						s_no = int(c)
						post_link = str(settings.API_SERVER) + str(i.image.name)
						view_limit = int(i.total_view)
						current_views = i.current_view
						if i.offensive == True:
							off = "Yes"
						if i.offensive == False:
							off ="No"
						writer.writerow([s_no,post_link,view_limit,current_views,off])
						c=c+1					
					return response
				else:
					message ,code,status = 'No Post Information.' ,200,'success'
			else:
				message ,code,status = 'Invalid User.',200,'success'

		except Exception as e :
			message ,code,status = 'Something went wrong :' +str(e) ,500,'error'

		return JsonResponse({'message': message ,'status' : status , 'code' : code })

class SinglePostCsv(APIView):
	def get(self,request):
		user_id = request.user.id
		if user_id:
			if 'post_id' not in request.GET:
				return JsonResponse({'message': 'post_id is missing.' ,'status' : 'success' , 'code' : 200 })
			else:
				if request.GET['post_id'] == None or request.GET['post_id'] == '':
					return JsonResponse({'message': 'Enter the value for the post_id','status' : 'success' , 'code' : 200 })
				else:
					post_id = request.GET.get('post_id')
					obj = OtherUsersReaction.objects.filter(post_id_id=int(post_id))
					response = HttpResponse(content_type='text/csv')
					response['Content-Disposition'] = 'attachment; filename="post_report.csv"'
					# separator = ','
					writer = csv.writer(response,delimiter=' ',
				                            escapechar=' ', quoting=csv.QUOTE_NONE)
					# writer.writerow(['Rank Submiited'])
					# writer = csv.writer(response)
					check_obj = UserAddedPost.objects.filter(id=int(post_id)).first()
					if check_obj:
						if int(check_obj.current_view) != int(check_obj.total_view):
							return JsonResponse({'message': 'Job is not completed.' ,'status' : 'success' , 'code' : 200 })
						else:
							if check_obj.offensive == True:
								rank_submitted = 'Is_offensive'
								writer.writerow([rank_submitted])
								return response
							else:
								for i in obj:   
									rank_submitted = i.rank
									# reacted_user_id = i.logged_user_id.id
									writer.writerow([rank_submitted])
								return response						
							return response
					else:
						message ,code,status = 'Invalid post_id.',200,'success'
		else:
			message ,code,status = 'Invalid User.',200,'success'
		return JsonResponse({'message': message ,'status' : status , 'code' : code })

class JobComplete(APIView):
	def get(self,request):
		try:
			user_id = request.user.id
			if user_id:
				if 'post_id' not in request.GET:
					return JsonResponse({'message': 'post_id is missing.' ,'status' : 'success' , 'code' : 200 })
				else:
					if request.GET['post_id'] == None or request.GET['post_id'] == '':
						return JsonResponse({'message': 'Enter the value for the post_id','status' : 'success' , 'code' : 200 })
					else:
						post_id = request.GET.get('post_id')
						obj1 = UserAddedPost.objects.filter(id=int(post_id)).first()
						if obj1:
							obj1.offensive = True
							obj1.offensive_at = int(obj1.current_view)
							obj1.current_view = obj1.total_view
							obj1.post_view_access = 0
							obj1.save()
							message,code,status = 'Successfully completed the job.',200,'success'
						else:
							message,code,status = 'Invalid post id.',200,'success'
			else:
				message ,code,status = 'Invalid User.',200,'success'
		except Exception as e:
			message ,code,status = 'Something went wrong :' +str(e) ,500,'error'
		return JsonResponse({'message': message ,'status' : status , 'code' : code })







# class UserPosts(ObtainAuthToken):
#     def get(self, request, *args, **kwargs):
#         response = super(UserPosts, self).get(request, *args, **kwargs)
#         token = Token.objects.get(key=response.data['token'])
#         return Response({'token': token.key, 'id': token.user_id})

