import os
import secrets
from PIL import Image
from wtforms import StringField, PasswordField, SubmitField, BooleanField
from flask import Flask, render_template, url_for, flash, redirect, request
from forms import UploadImage, AnalysisImage

from skimage.measure import compare_ssim as ssim
import matplotlib.pyplot as plt
import numpy as np
import cv2

from flask_images import Images
# from flask_images import Images
from flask_images import resized_img_src

app = Flask(__name__)
app.config['SECRET_KEY'] = '5791628bb0b13ce0c676dfde280ba245'
images = Images(app)


@app.route("/")
@app.route("/home")
def home():
    form = UploadImage()
    return render_template('home.html', form=form)


def save_picture(form_picture,x1,y1,x2,y2,width,height):
    random_hex = secrets.token_hex(8)
    _, f_ext = os.path.splitext(form_picture.filename)
    picture_fn1 = random_hex + f_ext
    picture_path1 = os.path.join(app.root_path, 'static/images', picture_fn1)
    print(f"Picture path {picture_path1}")
# https://auth0.com/blog/image-processing-in-python-with-pillow/
# http://jsfiddle.net/f5EMT/1/
    # output_size = (800, 800)
    
    # i.thumbnail(output_size)
    # area = (400, 400, 800, 800)
    # i = i.crop(area)
    i = Image.open(form_picture)

    if x1 and y1 and width:
        area = (int(x1),int(y1),int(x2),int(y2))
        
        i = i.crop(area)
        i = i.resize((800,800))
    else:
        # width, height = i.size
        i = i.resize((800, 800))


    i.save(picture_path1)

    i = i.convert("RGBA")
    datas = i.getdata()
    newData = []
    for item in datas:
        if item[0] == 255 and item[1] == 255 and item[2] == 255:
            newData.append((255, 255, 255, 0))
        else:
            newData.append(item)
                # print(item)


    i.putdata(newData)

    picture_fn2 = random_hex + "_.png"
    picture_path2 = os.path.join(app.root_path, 'static/images', picture_fn2)
    print(f"Picture path {picture_path2}")
    # i.save("open_science_logo_transparent.png", "PNG")

    i.save(picture_path2)

    return [picture_fn1,picture_fn2]


@app.route("/upload", methods=['GET', 'POST'])
def upload():
    form = UploadImage()
    if form.validate_on_submit():
        if request.method == "POST":
            x1 = request.form['x1']
            y1 = request.form['y1']
            x2 = request.form['x2']
            y2 = request.form['y2']
            width = request.form['width']
            height = request.form['height']
            print(x1)
            print(y1)
            print(x2)
            print(y2)
            print(width)
            print(height)
        if form.picture.data:
            picture_file = save_picture(form.picture.data,x1,y1,x2,y2,width,height)
            flash('File successfully uploaded!', 'success')
        # image_file = url_for('static', filename='images/' + picture_file)
        
        hide_upload_btn = True

        # image_addr = 'images/' + picture_file

        imagesFolder = os.path.join('static', 'images')

        tyresFolder = os.path.join('static', 'tyres')

        

        try:
            app.config['UPLOAD_FOLDER'] = imagesFolder
            image_to_check = os.path.join(app.config['UPLOAD_FOLDER'], picture_file[1])
            image_to_check1 = os.path.join(app.config['UPLOAD_FOLDER'], picture_file[0])
            
            a = cv2.imread(image_to_check)

            app.config['UPLOAD_FOLDER'] = tyresFolder
            
            tyre_mrf = os.path.join(app.config['UPLOAD_FOLDER'], 'a1.jpg')
            tyre_mrf1 = os.path.join(app.config['UPLOAD_FOLDER'], 'a1.png')
            b1 = cv2.imread(tyre_mrf1)

            tyre_ceat = os.path.join(app.config['UPLOAD_FOLDER'], 'a2.png')
            tyre_ceat1 = os.path.join(app.config['UPLOAD_FOLDER'], 'a21.png')
            b2 = cv2.imread(tyre_ceat1)

            tyre_tvs = os.path.join(app.config['UPLOAD_FOLDER'], 'a3.jpg')
            tyre_tvs1 = os.path.join(app.config['UPLOAD_FOLDER'], 'a3.png')
            b3 = cv2.imread(tyre_tvs1)

            tyre_dunlop = os.path.join(app.config['UPLOAD_FOLDER'], 'a4.png')
            b4 = cv2.imread(tyre_dunlop)

            tyre_bridgestone = os.path.join(app.config['UPLOAD_FOLDER'], 'a5.png')
            tyre_bridgestone1 = os.path.join(app.config['UPLOAD_FOLDER'], 'a51.png')
            b5 = cv2.imread(tyre_bridgestone1)

            list_tyre = [b1,b2,b3,b4,b5]

            result = []

            for tyre in list_tyre:
                result_ = ssim(a, tyre, multichannel=True)
                result.append(result_)

            for i in range(len(result)):
                result[i] = int(round(result[i] * 100))

            dict_tyre = {'MRF Tyres':[result[0],tyre_mrf], 'CEAT Tyres':[result[1],tyre_ceat], 'TVS Tyres':[result[2],tyre_tvs], 'Dunlop Tyres':[result[3],tyre_dunlop], 'Bridgestone Tyres':[result[4],tyre_bridgestone]}
            
            max1 = result[0]
            max_result = 'The image got '+str(max1)+'% match with MRF Tyres.'
            for (x,y) in dict_tyre.items():
                if max1<y[0]:
                    max1 = y[0]
                    max_result = "The image got "+str(y[0])+"% match with "+x+"."
            
            if max1<50:
                max_result = "The image doest not match."
            # a = cv2.imread(r'/home/divija/PYTHON Practice/tyres/t1.png')
            # b = cv2.imread(r'/home/divija/PYTHON Practice/tyres/t1.png')
            
            
            # result = ssim(a,b, multichannel=True)
            # result = result * 100
            # result = str(result) + " % matched"
            error_msg = ''
        except ValueError:
            max_result=''
            dict_tyre=''
            result = '0% matched.'
            error_msg = 'Input images must have the same dimensions.'
        except:
            return render_template('home.html', form=form)
        return render_template('home.html', max_result=max_result, dict_tyre=dict_tyre, error_msg=error_msg, image_file=image_to_check1, hide_upload_btn=hide_upload_btn, form=form)
        
    elif request.method == 'GET':
        msg=""
    return render_template('home.html', title='Account', form=form)

@app.route("/analyse", methods=['GET', 'POST'])
def analyse():
    form = AnalysisImage()








if __name__ == '__main__':
    app.run(debug=True)