from django import views
from django.shortcuts import render
from .models import *
from .serializers import *
from rest_framework import viewsets,views
from rest_framework.response import Response
import os
import csv
import sys

#from sitcomm.conf import *

class UserViewSet(viewsets.ModelViewSet):
    queryset = Users.objects.all()
    serializer_class = UserSerializer

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Projects.objects.all()
    serializer_class = ProjectSerializer

class AccessViewSet(viewsets.ModelViewSet):
    queryset = Access.objects.all()
    serializer_class = AccessSerializer

class JiraViewSet(viewsets.ModelViewSet):
    queryset = Tickets.objects.all()
    serializer_class = JiraSerializer

# Create your views here.

class checkAuthViewSet(views.APIView):
    def get(self,request):
        uid = request.GET.get('uid')
        try:
            user = Users.objects.get(uid=uid)
            return Response({'status':True})
        except:
            return Response({'status':False})

class authenticateViewSet(views.APIView):
    def post(self,request):
        email = request.data.get('email')
        password = request.data.get('password')
        #print(email,password)
        try:
            user = Users.objects.filter(email=email)
            #print(user)
            user = user.filter(password=password)
            uid = user[0].uid
            #print(user, len(user), user is None)
            if len(user) == 0:
                return Response({'status':False})
            status = user.update(active=True)
            return Response({'email':email, 'uid':uid,'status':bool(status)})
        except:
            return Response({'status':False})

class registerViewSet(views.APIView):
    def post(self,request):
        try:
            print("Registering user")
            email = request.data.get('email')
            password = request.data.get('password')
            role = request.data.get('role')
            first_name = request.data.get('first_name')
            last_name = request.data.get('last_name')
            #print(email,password,role)
            user = Users.objects.create(email=email,password=password,role=role,first_name=first_name,last_name=last_name)
            return Response({'uid':user.uid,'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

class getJiraTicketsViewSet(views.APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        try:
            project = Tickets.objects.filter(pid=pid)
            if len(project) == 0:
                return Response({'status':False})
            return Response({'files':project.values(),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

class getJiraBoardViewSet(views.APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        status = 'All'
        try:
            if request.GET.get('status') is not None:
                col_name = request.GET.get('status')
        except:
            pass
        try:
            project = Projects.objects.filter(pid=pid)
            if project is None:
                return Response({'status':False})
            tickets = Tickets.objects.filter(pid=pid)
            if tickets is None:
                return Response({'status':False})
            if col_name != 'All':
                tickets = tickets.filter(status=status)
            return Response({'tickets':tickets.values(),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})


class createJiraTicketViewSet(views.APIView):
    def post(self,request):
        pid = request.data.get('pid')
        name = request.data.get('name')
        content = request.data.get('content')
        status = request.data.get('status')
        matching_projects = Projects.objects.filter(pid=pid)
        try:
            ticket = Tickets.objects.create(pid=matching_projects[0],name=name,content=content,status=status)
            return Response({'tid':ticket.tid,'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

class updateJiraTicketViewSet(views.APIView):
    def post(self,request):
        tid = request.data.get('tid')
        status = request.data.get('status')
        try:
            ticket = Tickets.objects.filter(tid=tid)
            if len(ticket) == 0:
                return Response({'status':False})
            ticket.update(status=status)
            return Response({'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})



class getReposViewSet(views.APIView):
    def get(self,request):
        uid = request.GET.get('uid')
        print(uid)
        try:
            user = Users.objects.filter(uid=uid)
            if len(user) == 0:
                print("User not found")
                return Response({'status':False})
            access = Access.objects.filter(uid=uid).values('pid').distinct()
            try:
                print('finding pid in access')
                repos = Projects.objects.filter(pid__in=access)
                #print("Projects",Projects.objects.values())
            except Exception as e:
                print(e)
            return Response({'repos':repos.values(),'status':True})
        except:
            return Response({'status':False})

class getGitFilesViewSet(views.APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        try:
            project = Projects.objects.filter(pid=pid)
            if project is None:
                return Response({'status':False})
            return Response({'files':project.values('git_id'),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

class postFileChangeViewSet(views.APIView):
    def post(self,request):
        pid = request.data.get('pid')
        file = request.data.get('file_id')
        data = request.data.get('content')
        try:
            project = Projects.objects.filter(pid=pid)
            if len(project) == 0:
                return Response({'status':False})
            git_id = project.values('git_id')[0]['git_id']
            relative_path = '../frontend/sitcomm/src/assets/'
            #print(os.getcwd())
            git_id = relative_path + git_id
            #print(git_id)
            orig_file = open(git_id,'r')
            orig_dt = csv.DictReader(orig_file)
            update_file = []
            for line in orig_dt:
                #print(line)
                print(line['id'],file)
                if line['id'] == file:
                    line['content'] = data
                update_file.append(line)
            orig_file.close()
            #print(git_id)
            orig_file = open(git_id,'w')
            headers = ['id','name','commitMessage','commitDate','type','content']
            data = csv.DictWriter(orig_file,fieldnames=headers,delimiter=',')
            data.writerow(dict((fn,fn) for fn in headers))
            data.writerows(update_file)
            print(update_file)
            orig_file.close()

            '''
            with open (git_id,'w+') as f:
                print("Writing to file")
                print(git_id)
                csvFile = csv.reader(f)
                for row in csvFile:
                    print(row)
                    if row[0] == file:
                        row[1] = data
                        writer = csv.writer(f)
                        writer.writerow(row)
                        print(row)
            '''
            return Response({'status':True})
        except Exception as e:
            print("error",e)
            return Response({'status':False})

class postFileCreateViewSet(views.APIView):
    def post(self,request):
        pid = request.data.get('pid')
        file = request.data.get('file')
        data = request.data.get('data')
        try:
            project = Projects.objects.filter(pid=pid)
            if project is None:
                return Response({'status':False})
            git_id = project.values('git_id')[0]['git_id']
            with open (git_id,'a') as f:
                writer = csv.writer(f)
                writer.writerow([file,data])
            return Response({'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})


class getUserDetailsViewSet(views.APIView):
    def get(self,request):
        uid = request.GET.get('uid')
        try:
            user = Users.objects.filter(uid=uid)
            if len(user) == 0:
                return Response({'status':False})
            return Response({'user':user.values(),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

    
class postUserDetailsViewSet(views.APIView):
    def post(self,request):
        try:
            uid = request.data.get('uid')
            first_name = request.data.get('first_name')
            last_name = request.data.get('last_name')
            bio = request.data.get('bio')
            profile_img = request.data.get('profile_img')
            #print(uid,first_name,last_name,bio,profile_img)
            #return Response({'status':False})
            user = Users.objects.filter(uid=uid)
            if len(user) == 0:
                return Response({'status':False})
            status = user.update(first_name=first_name,last_name=last_name,bio=bio,profile_img=profile_img)
            return Response({'status':bool(status)})
        except Exception as e:
            print(e)
            return Response({'status':False})

class getConfluencePagesViewSet(views.APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        try:
            project = Projects.objects.filter(pid=pid)
            if project is None:
                return Response({'status':False})
            return Response({'pages':project[0].values('confluence_id'),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})


class getProjectDetailsViewSet(views.APIView):
    def get(self,request):
        pid = request.GET.get('pid')
        try:
            project = Projects.objects.filter(pid=pid)
            if project is None:
                return Response({'status':False})
            return Response({'project':project.values(),'status':True})
        except Exception as e:
            print(e)
            return Response({'status':False})

            
