import base64
import json
from django.http import JsonResponse
from django.views import View
from PIL import Image
from snow_flake.models import *
from django.db.models import *
import math


class UpdateDepartmentVisibility(View):

    def applyDepartmentVisibility(self,startDepartmentId):
        isSuccess = False
        message = 'Required a Number'
        
        if startDepartmentId is not None:
            id = startDepartmentId
            isSameLength = False
            if id is not None:
                count = 0
                selectedList = Department.objects.filter(id__gte=id)
                tempList = selectedList.filter(isVisible=True)
                if tempList.__len__() == selectedList.__len__():
                    isSameLength = True

                if isSameLength == False:
                    for selected in selectedList:
                        selected.isVisible = True
                        selected.save()
                        count = count + 1

                    if count == selectedList.__len__():
                        isSuccess = True
                        message = 'All records have been updated'
                    else:
                        isSuccess = False
                        message = 'Not All records have been updated'
                else:
                    isSuccess = False
                    message = 'All the records are already updated'
        return isSuccess, message

    def applyDepartmentPopular(self):
        isSuccessPopular = False
        messagePopular = 'Sub departments not Popular'

        Department.objects.update(isPopular = False)

        mainDepartmentList = Department.objects.filter(departmentId = None)
        popularCount = 0
        for i in mainDepartmentList:
            popularCount = popularCount + self.updatePopular(i)

        count = Department.objects.filter(isPopular = True).count()
        if count == popularCount:
            isSuccessPopular = True
            messagePopular = 'Sub departments are Popular now'
        
        return isSuccessPopular,messagePopular,popularCount

    def updatePopular(self,mainDepartment):
        subDepartmentList = Department.objects.filter(departmentId = mainDepartment.id)
        count = 0
        if subDepartmentList.__len__() > 0:
            for i in subDepartmentList:
                count = count + self.updatePopular(i)
        else:
            mainDepartment.isPopular = True
            mainDepartment.isUseItemImageLink = True
            mainDepartment.save()
            count = count + 1
        return count
    
    def applyDepartmentSelected(self):
        isSuccessSelected = False
        messageSelected = 'Sub departments not Selected'

        Department.objects.update(isSelected = False)
        mainDepartmentList = Department.objects.filter(departmentId = None)
        selectedCount = 0
        for i in mainDepartmentList:
            selectedCount = selectedCount + self.updateSelected(i)
        
        count = Department.objects.filter(isSelected = True).count()
        if count == selectedCount:
            isSuccessSelected = True
            messageSelected = 'Sub departments are Selected now'
        
        return isSuccessSelected,messageSelected,selectedCount
    
    def updateSelected(self,mainDepartment):
        subDepartmentList = Department.objects.filter(departmentId = mainDepartment.id).order_by('-createdDate')
        count = 0
        if subDepartmentList.__len__() > 0:
            count = count + self.updateSelected(subDepartmentList[0])
        else:
            mainDepartment.isSelected = True
            mainDepartment.save()
            count = count + 1
        return count

    def post(self, request, *args, **kwargs):
        startDepartmentId = None
        jsonData = json.loads(request.body)

        if jsonData.__len__() > 0:
            if "startDepartmentId" in jsonData:
                startDepartmentId = jsonData["startDepartmentId"]
        
        isSuccess,message = self.applyDepartmentVisibility(startDepartmentId)

        isSuccessPopular,messagePopular,popularCount = self.applyDepartmentPopular()

        isSuccessSelected,messageSelected,selectedCount = self.applyDepartmentSelected()

        return JsonResponse(
            {
                "startDepartmentId": startDepartmentId,
                "isSuccess": isSuccess,
                "message": message,
                "isSuccessPopular":isSuccessPopular,
                "messagePopular":messagePopular,
                "popularCount":popularCount,
                "isSuccessSelected":isSuccessSelected,
                "messageSelected":messageSelected,
                "selectedCount":selectedCount
            },
            safe=False,
        )


class UpdateBrandVisibility(View):
    def post(self, request, *args, **kwargs):
        startBrandId = None
        jsonData = json.loads(request.body)
        if jsonData.__len__() > 0:
            if "startBrandId" in jsonData:
                startBrandId = jsonData["startBrandId"]

        if startBrandId is not None:
            id = startBrandId
            isSameLength = False
            if id is not None:
                count = 0
                selectedList = Brand.objects.filter(id__gte=id)
                tempList = selectedList.filter(isVisible=True)
                if tempList.__len__() == selectedList.__len__():
                    isSameLength = True

                if isSameLength == False:
                    for selected in selectedList:
                        selected.isVisible = True
                        selected.isUseItemImageLink = True
                        selected.save()
                        count = count + 1

                    if count == selectedList.__len__():
                        return JsonResponse(
                            {
                                "startBrandId": startBrandId,
                                "isSuccess": True,
                                "message": "All records have been updated",
                            },
                            safe=False,
                        )
                    else:
                        return JsonResponse(
                            {
                                "startBrandId": startBrandId,
                                "isSuccess": False,
                                "message": "Not All records have been updated",
                            },
                            safe=False,
                        )
                else:
                    return JsonResponse(
                        {
                            "startBrandId": startBrandId,
                            "isSuccess": False,
                            "message": "All the records are already updated",
                        },
                        safe=False,
                    )

        return JsonResponse(
            {
                "startBrandId": startBrandId,
                "isSuccess": False,
                "message": "Invalid Number",
            },
            safe=False,
        )


class BulkResetSKU(View):
    def post(self, request, *args, **kwargs):
        totalUpdatedRecord = SKU.objects.all().update(amount=0)
        totalRecords = SKU.objects.count()
        isSuccess = False
        message = "Not All records have been reset"
        if totalUpdatedRecord == totalRecords:
            isSuccess = True
            message = "All records have been reset"
        return JsonResponse(
            {
                "isSuccess": isSuccess,
                "totalUpdatedRecord": totalUpdatedRecord,
                "totalRecords": totalRecords,
                "message": message,
            },
            safe=False,
        )


class SetDiscount(View):
    def post(self, request, *args, **kwargs):
        jsonData = json.loads(request.body)
        totalTopSKUs = 0
        totalFavoriteSKUs = 0
        for x in jsonData["discountList"]:
            name = x["name"]
            discountVal = x["discount"]

            if name == "topProducts":
                totalTopSKUs = (
                    SKU.objects.filter(itemId__isApproved=True)
                    .filter(itemId__isTop=True)
                    .update(discount=discountVal)
                )
            elif name == "favoriteProducts":
                totalFavoriteSKUs = (
                    SKU.objects.filter(itemId__isApproved=True)
                    .filter(itemId__isFavorite=True)
                    .update(discount=discountVal)
                )

        return JsonResponse(
            {
                "isSuccess": True,
                "totalTopSKUs": totalTopSKUs,
                "totalFavoriteSKUs": totalFavoriteSKUs,
            },
            safe=False,
        )


class BulkUpdateProductSelection(View):
    
    def post(self, request, *args, **kwargs):
        Item.objects.update(isTop=False,isFavorite=False,isMostDiscount = False,isMostViewed = False,isNewArrival=False)
        
        SKU.objects.update(isTop=False,isFavorite=False,isMostDiscount = False,isMostViewed = False,isNewArrival=False)
        
        count = Item.objects.count()

        splitCount =  math.floor( count / 2)
        
        # for i in range(0,count):
        #     itemList = Item.objects.filter(item_itemlanguage__name__contains = shapeList[i].shapeName)
        #     if i < 6:
        #         for j in range(0,1):
        #             itemList[j].isNewArrival = True
        #             itemList[j].save()
        #             selectedSKU = SKU.objects.filter(itemId = itemList[j].id).first()
        #             if selectedSKU is  not None:
        #                 selectedSKU.isNewArrival = True
        #                 selectedSKU.save()
                        
        #     if i < splitCount:
        #          for j in range(0,len(itemList)):
        #             selectType = None
        #             if i % 2 == 0:
        #                 itemList[j].isTop = True
        #                 itemList[j].isFavorite = False
        #                 selectType = 1
        #             else:
        #                 itemList[j].isTop = False
        #                 itemList[j].isFavorite = True
        #                 selectType = 2
                        
        #             itemList[j].save()
                    
        #             if j  == 0:
        #                 if selectType is not None:
        #                     selectedSKU = SKU.objects.filter(itemId = itemList[j].id).first()
        #                     if selectedSKU is  not None:
        #                         if selectType == 1:
        #                             selectedSKU.isTop = True
        #                         else:
        #                             selectedSKU.isFavorite = True
        #                         selectedSKU.save()

        #     else:
        #         for j in range(0,len(itemList)):
        #             selectType = None
        #             if i % 2 == 0:
        #                 itemList[j].isMostDiscount = True
        #                 itemList[j].isMostViewed = False
        #                 selectType = 1
        #             else:
        #                 itemList[j].isMostDiscount = False
        #                 itemList[j].isMostViewed = True
        #                 selectType = 2
                    
        #             itemList[j].save()
                    
        #             if j == 0:
        #                 if selectType is not None:
        #                     selectedSKU = SKU.objects.filter(itemId = itemList[j].id).first()
        #                     if selectedSKU is  not None:
        #                         if selectType == 1:
        #                             selectedSKU.isMostDiscount = True
        #                         else:
        #                             selectedSKU.isMostViewed = True
        #                         selectedSKU.save()

        return JsonResponse(
            {
                "isSuccess": False,
                "message": "Success",
            },
            safe=False,
        )


class DownloadSKUImageView(View):

    def changeBackground(self, imagePath):
        pathList = imagePath.split("/")
        newNamList = []
        imageName = ""
        if pathList.__len__() > 0:
            newNamList = pathList[-1].split(".")
            if newNamList.__len__() > 0:
                imageName = newNamList[0]

        newPath = ""
        for p in pathList[0:-1]:
            newPath = newPath + p + "/"

        if imageName != "":
            newPath = newPath + imageName + ".jpg"
            im = Image.open(imagePath)

            fill_color = (255, 255, 255)  # your new background color white

            im = im.convert("RGBA")  # it had mode P after DL it from OP
            if im.mode in ("RGBA", "LA"):
                background = Image.new(im.mode[:-1], im.size, fill_color)
                background.paste(im, im.split()[-1])  # omit transparency
                im = background

            im.convert("RGB").save(newPath)
        return newPath

    def post(self, request, *args, **kwargs):
        skuId = None
        jsonData = json.loads(request.body)
        if jsonData.__len__() > 0:
            if "skuId" in jsonData:
                skuId = jsonData["skuId"]

        if skuId is not None:
            id = skuId
            selectedSKU = SKU.objects.get(id=id)
            if selectedSKU is not None:
                imagePath = selectedSKU.image.path
                newPath = self.changeBackground(imagePath)
                with open(newPath, "rb") as img_file:
                    my_string = base64.b64encode(img_file.read())
                os.remove(newPath)
                return JsonResponse(
                    {
                        "image": my_string.decode("utf-8"),
                        "isSuccess": True,
                        "message": "image is downloaded",
                    },
                    safe=False,
                )
        return JsonResponse(
            {
                "isSuccess": False,
                "message": "image is downloaded",
            },
            safe=False,
        )