from django.shortcuts import render

from django.contrib.auth.hashers import make_password
from django.contrib.auth import logout

from django.conf import settings
from django.db import connection

from asset_management_app import models
from asset_management_app import serializers
from asset_management_app import utils

from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from rest_framework.generics import GenericAPIView



import pandas as pd



class assetLocationAPIview(GenericAPIView):
    Permission =[IsAuthenticated]
    def post(self,request):
        try :
            # id  =  request.user.pk
            location =  request.data["location"]
            # if not models.users.objects.filter(id =   id).exists():
            #              return Response({"statusCode": "0", "statusMessage": "Failed", "error": "Id does not exists"})
            serializer = serializers.create_asset_location_serializer(data=request.data)                 
            serializer.is_valid(raise_exception=True)                 
            serializer.save() 
            return Response({"statusCode":"1","statusMessage":"Success","data":serializer.data})
        except  Exception as e:
            return Response({"statusCode":"0","statusMessage":str(e)})
    
    def get(self,request):
        try:
            # id  =  request.user.pk
            location_id =  request.GET.get("location_id",None)
            if location_id is not None:
                result = get_location_byid(location_id)
                return Response({"statusCode":"1","statusMessage":"Success","data":result})
            else:
                result =  get_location_byall()
                return Response({"statusCode":"1","statusMessage":"Success","data":result})
        except  Exception as e:
            return Response({"statusCode":"0","statusMessage":str(e)})
        
    def patch(self,request):
        try:
            location_id =  request.GET.get("location_id",None)
            if models.asset_location.objects.filter(id = location_id).exists():
                    qs_location_info = models.asset_location.objects.get(id = location_id)
                    serializer_location = serializers.create_asset_location_serializer(qs_location_info, data=request.data, partial=True)
                    serializer_location.is_valid(raise_exception=True)
                    serializer_location.save()
                    return Response({"statusCode":"1","statusMessage":"success","data":serializer_location.data})
            else:
                return Response({"statusCode": "0", "statusMessage": "Failed","error":"Mismatch Id"})
        except  Exception as e:
            return Response({"statusCode":"0","statusMessage":str(e)})
    
    def delete(self,request):
        try:
            location_id =  request.GET.get("location_id",None)
            delete_db =  request.GET.get("delete_db",None)
            if delete_db is not None:
                if models.asset_location.objects.filter(id = location_id).exists():
                    qs_location_info = models.asset_location.objects.get(id = location_id)                 
                    qs_location_info.delete()
                    return Response({"statusCode": "1", "statusMessage":"Scuccess","data":"location deleted successfully"})
                else:
                    return Response({"statusCode": "0", "statusMessage": "Failed","data":"Mismatch Id"})
            else:
                    
                    if models.asset_location.objects.filter(id = location_id).exists():
                        request.data['is_deleted']  = "1"
                        qs_location_info = models.asset_location.objects.get(id = location_id)
                        serializer_location = serializers.create_asset_location_serializer(qs_location_info, data=request.data, partial=True)
                        serializer_location.is_valid(raise_exception=True)
                        serializer_location.save()
                        return Response({"statusCode": "1", "statusMessage":"Success","data": "location deleted successfully"})
                    else:
                        return Response({"statusCode": "0", "statusMessage": "Failed","error":"Mismatch Id"})
        except  Exception as e:
            return Response({"statusCode":"0","statusMessage":str(e)})
              
                    
      

   
        
        

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [ 
        dict(zip(columns, row))
        for row in cursor.fetchall()
    ]


def get_location_byid(id):
    param = {'uid':id}
    rows = []
    with connection.cursor() as cur:
        cur.execute(''' SELECT  id, asset_id, name, location, installation_date, removel_date, notes, installed_by, important_notes, is_active, is_deleted, created_at, updated_at
                    FROM  asset_db.asset_management_app_asset_location  where  id = %(uid)s''', param)
        rows = dictfetchall(cur)
    return rows

def get_location_byall():
    param = {}
    rows = []
    with connection.cursor() as cur:
        cur.execute(''' SELECT  id, asset_id, name, location, installation_date, removel_date, notes, installed_by, important_notes, is_active, is_deleted, created_at, updated_at
                    FROM asset_db.asset_management_app_asset_location''', param)
        rows = dictfetchall(cur)
    return rows
