from urllib.parse import urljoin
import requests
import json
import datetime
import re
import io
from autocapture_model import detector
import numpy as np
import PIL.Image
import os

USERNAME = 'nathan'
PASSWORD =  'Driving a Volkswagon Vanagon is like stirring a pot~'
DAYS_BACK_RANGE = 1

today = datetime.datetime.today()
end_date = today - datetime.timedelta(days=DAYS_BACK_RANGE)

auth_body = {'requested_url':'', 'username': USERNAME,'passphrase': PASSWORD}

session = requests.Session()
response = session.post("https://mlweb-staging.ml.prod.trulioo.com/authenticate", data=auth_body)

request_body = {"end_date":end_date.isoformat(), "start_date":today.isoformat(), "target":"barcode"}
# request_body = {"target":"barcode"}
request_headers = {'Content-Type': 'application/json'}
# print(request_body)
response = requests.post("https://mlweb-staging.ml.prod.trulioo.com/get_results", data=json.dumps(request_body), headers=request_headers)

extract_id = re.findall(r'"id"[:] "[0-9a-zA-Z-]+', str(response.content))
all_images_id_list = [x[7:] for x in extract_id]

base_url = 'https://mlweb-staging.ml.prod.trulioo.com'

assert len(all_images_id_list) > 0, "No images ids found"

print(f"{len(all_images_id_list)} barcodes ids available in last {DAYS_BACK_RANGE} days.")
images = []
document_detector = detector.DocumentDetector()
root = '/data/doc_detect/barcodes/mlweb_dump/'
count = 0
total = 0
for image_idx, image_id in enumerate(all_images_id_list):
    try:
        image_url = urljoin(base_url, f'/images/{image_id}')
        # Send a GET request to fetch the image data
        response = session.get(image_url)
        image_bytes = io.BytesIO(response.content)
        image = PIL.Image.open(image_bytes)
        # Check if the image is in RGBA mode
        if image.mode == 'RGBA':
            image = image.convert('RGB')
        # images.append([image, image_id])
        result = document_detector.detect_document(name='test', image=image)
        if result[0] is True:
            pad_x = 20
            pad_y = 20
            box = result[1]['raw_result']['barcode']['original_box']
            im_arr = np.array(image)
            im_arr = im_arr[box[1]-pad_y:box[3]+pad_y, box[0]-pad_x:box[2]+pad_x]

            filename = image_id + '.jpg'
            if filename not in os.listdir(root):
                PIL.Image.fromarray(im_arr).save(root + filename)
                count += 1

            images.append([PIL.Image.fromarray(im_arr), image_id])
            total += 1
    except Exception as e:
        continue
        print('Error:', e)
print(count, total, 'new barcodes added')