from flask import Flask, request, jsonify
import cv2
import numpy as np
import pytesseract
import matplotlib.pyplot as plt
from PIL import Image
import os
# from google.colab import files

app = Flask(__name__)


@app.route('/', methods=['GET'])
def hello():
    return jsonify({'response': 'Hello, Flask!'})


# @app.route('/test-form', methods=['POST'])
# def test_form():
#     nama = request.form['nama']
#     return jsonify({'response': f'Halo, {nama}!'})


# @app.route('/test-form-image', methods=['POST'])
# def test_form_image():
#     # image = request.form['image']
#     # all_data = {**request.args.to_dict(), **request.form.to_dict(),
#     #             **request.files.to_dict()}
#     # return jsonify(request.files)
#     if 'image' in request.files:
#         uploaded_file = request.files['image']
#         # Melihat informasi tentang file
#         # print(f"File Name: {uploaded_file.filename}")
#         # print(f"Content Type: {uploaded_file.content_type}")
#         if uploaded_file.filename == '':
#             return 'No selected file'

#         # Mendapatkan lokasi dari file Python yang sedang berjalan
#         current_directory = os.path.dirname(os.path.abspath(__file__))
#         uploaded_file.save(os.path.join(
#             current_directory, uploaded_file.filename))

#         return 'File berhasil diunggah dan disimpan!'
#         # Anda dapat melakukan operasi lain di sini dengan file yang diunggah
#         # Misalnya, menyimpannya ke sistem file dengan:
#         # uploaded_file.save('lokasi_direktori_dan_nama_file_yang_diinginkan')
#         # return 'File berhasil diunggah!'
#     else:
#         return 'Tidak ada file yang diunggah!'


@app.route('/process-image', methods=['POST'])
def process_image():
    if 'image' in request.files:
        uploaded_file = request.files['image']
        if uploaded_file.filename == '':
            return 'Tidak ada File yang dipih'

        current_directory = os.getcwd()
        file_directory = os.path.join(
            current_directory, uploaded_file.filename)
        uploaded_file.save(file_directory)
    else:
        return 'Tidak ada file yang diunggah!'

    try:
        if uploaded_file is not None:
            # Lakukan proses pada data gambar, misalnya menggunakan OpenCV
            # Simpan hasil dalam variabel `result`

            # Membaca gambar dengan OpenCV
            image = open(file_directory, "rb")
            image_data = image.read()
            image_array = bytearray(image_data)
            nparr = np.frombuffer(image_array, np.uint8)
            img_cv2 = cv2.imdecode(nparr, cv2.IMREAD_COLOR)

            # read img
            gray = cv2.cvtColor(img_cv2, cv2.COLOR_BGR2GRAY)

            # (2) Threshold
            th, threshed = cv2.threshold(gray, 127, 255, cv2.THRESH_TRUNC)

            # (3) Detect
            result = pytesseract.image_to_string((threshed), lang="ind")

            hasil = result.split("\n")

            if os.path.exists(file_directory):
                os.remove(file_directory)

            return jsonify({'status': 'Berhasil', 'result': hasil})
        else:
            return jsonify({'error': 'No image uploaded'})

        # return jsonify(word)
    except Exception as e:
        return jsonify(error=str(e))