import cv2
import numpy as np
import requests
import time
import os
import threading


def delet_file(file):
    time.sleep(120)
    os.remove(file)


# load image from url
def urlToImage(url):
    # download image,convert to a NumPy array,and read it into opencv
    resp = requests.get(url)
    img = np.asarray(bytearray(resp.content),dtype="uint8")
    img = cv2.imdecode(img,cv2.IMREAD_COLOR)

    #return the image
    return img
def blend_with_mask_matrix(src1, src2, mask):
    res_channels = []
    for c in range(0, src1.shape[2]):
        a = src1[:, :, c]
        b = src2[:, :, c]
        m = mask[:, :, c]
        res = cv2.add(
            cv2.multiply(b, cv2.divide(np.full_like(m, 255) - m, 255.0, dtype=cv2.CV_32F), dtype=cv2.CV_32F),
            cv2.multiply(a, cv2.divide(m, 255.0, dtype=cv2.CV_32F), dtype=cv2.CV_32F),
           dtype=cv2.CV_8U)
        res_channels += [res]
    res = cv2.merge(res_channels)
    return res
    
def operation(url):
    # img=urlToImage(url)
    # height,width=img.shape[0:2]
    # #Startoperation
    # thresh=cv2.inRange(img[int((height/6)*5)+50:height,int((width/5)*4):width],np.array([150,150,150]),np.array([255,255,255]))

    # kernel = np.ones((5, 5), 'uint8')

    # dilate_img = cv2.dilate(thresh, kernel, iterations=1)
    # scan=np.ones((3,3),np.uint8)
    # # cor=cv2.dilate)
    # specular = cv2 . inpaint ( img[int((height/6)*5)+50:height,int((width/5)*4):width] , dilate_img , 5 , flags = cv2 . INPAINT_TELEA ) 

    # img[int((height/6)*5)+50:height,int((width/5)*4):width] = specular
 
    # file_name = "./static/temp_img/"+url.split("/")[-1]
    # cv2.imwrite(file_name,img)
    # threading.Thread(target=delet_file,args=[file_name]).start()
    # return url.split("/")[-1]
    img=urlToImage(url)
    height,width=img.shape[0:2]
    print(img.shape)
    mask = np.full((height,width, 3),255, dtype= np.uint8)
    mask[int((height/6)*5):height,int((width/5)*4):width] = np.zeros((int(height)-int((height/6)*5), int(width)-int((width/5)*4), 3), dtype = "uint8")
    roi = cv2.blur(img,(100,100))
    mask = cv2.blur(mask,(50,50))
    img2 = img
    file_name = "./static/temp_img/"+url.split("/")[-1]
    cv2.imwrite(file_name,blend_with_mask_matrix(img2, roi, mask))
    threading.Thread(target=delet_file,args=[file_name]).start()
    return url.split("/")[-1]

# cv2.imshow("asdas",specular)
# cv2.imwrite("milan.jpg",img)
def remove_whatermak(url):
    filename = operation(url)
    return "http://172.105.57.151/static/temp_img/"+filename




# remove_whatermak("https://photolabme-images.ws.pho.to/t/r/87309de8533d58b88faa681e09dd8244d41a739e.jpeg")
