import base64
import os
import tempfile
from collections import Counter
from io import BytesIO

import cv2
import requests
from PIL import Image
from sklearn.cluster import KMeans
from werkzeug.utils import secure_filename

from configs.firebase import db
from functions.Response import API_Error

# from skimage.color import rgb2lab, deltaE_cie76

def RGB2HEX(color):
    return "#{:02x}{:02x}{:02x}".format(int(color[0]), int(color[1]), int(color[2]))

def get_file_path(filename):
    # Note: tempfile.gettempdir() points to an in-memory file system
    # on GCF. Thus, any files in it must fit in the instance's memory.
    file_name = secure_filename(filename)
    return os.path.join(tempfile.gettempdir(), file_name)

def get_image(image_path):
    image = cv2.imread(image_path)
    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
    return image

def get_colors(image,number_of_colors=5, show_chart=False):
    modified_image = cv2.resize(image, (600, 400), interpolation = cv2.INTER_AREA)
    modified_image = modified_image.reshape(modified_image.shape[0]*modified_image.shape[1], 3)
    clf = KMeans(n_clusters = number_of_colors)
    labels = clf.fit_predict(modified_image)
    counts = Counter(labels)
    center_colors = clf.cluster_centers_
    # We get ordered colors by iterating through the keys
    ordered_colors = [center_colors[i] for i in counts.keys()]
    hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()]
    rgb_colors = [ordered_colors[i] for i in counts.keys()]
    ordercounts = ({RGB2HEX(ordered_colors[key]):counts[key] for key in counts.keys()})
    return list(hex_colors), list(rgb_colors),ordercounts

# def calculate_perctage(colors, total):
    # return [int(round(100 * i / total)) for i in colors]

def download_image_from_url(url):

    response = requests.get(url)
    path = get_file_path("myimage.png")
    img = Image.open(BytesIO(response.content))
    img.save(path)
    return path