# -*- coding: utf-8 -*-
import configparser
from ctypes import cdll
import json
import logging
import subprocess
import time
import threading

import RPi.GPIO as GPIO
import pygame

import uploader


cdll.LoadLibrary('/usr/lib/arm-linux-gnueabihf/libX11.so.6')
cdll.LoadLibrary('/usr/lib/arm-linux-gnueabihf/libX11-xcb.so.1')
PIN_BUTTON = 21
GPIO.setmode(GPIO.BCM)
GPIO.setup(PIN_BUTTON, GPIO.IN, pull_up_down=GPIO.PUD_UP)  # input

LOGGER = logging.getLogger(__name__)


def get_config():
    """Read config from ./config.json"""
    with open('config.json', 'r') as config_file:
        config = json.load(config_file)
    return config


def get_file_name(prefix="photobox", path="~"):
    # name mit Timestamp versehen
    ts = time.gmtime()
    readable_ts = time.strftime("%H_%M_%S", ts)
    photo_name = "/" + prefix + readable_ts + ".jpg"
    return path + photo_name


def display_qr(screen, qr):
    screen.blit(qr, (1330, 700))
    pygame.display.flip()
    pygame.display.update()


def load_image(img_path):
    image = pygame.image.load(img_path)
    image = image.convert()  # Convert the image to the display format
    return image

def display_image(screen, img, width, height):
    try:
        img = pygame.transform.scale(img, (width, height))
        screen.blit(img, (0, 0))
    except:
        print("Failled to display image")
    pygame.display.flip()
    pygame.display.update()


def display_text(screen, text, color=(20, 240, 100), size=70):
    font = pygame.freetype.Font(
        "/usr/share/fonts/truetype/liberation2/LiberationSans-Bold.ttf", size
    )
    text_renderd, text_rect = font.render(text, color)
    screen_rect = screen.get_rect()
    text_rect.centerx = screen_rect.centerx
    screen.blit(text_renderd, (50, 50))
    pygame.display.update()


def io_remote():
    # wait for button press
    GPIO.wait_for_edge(PIN_BUTTON, GPIO.BOTH, bouncetime=100)
    print("button pressed")

def signal_hook(running=True):
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
                pygame.quit()
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_f:
                pygame.display.toggle_fullscreen()

def buttonPressed():
    LOGGER.debug(GPIO.input(PIN_BUTTON))
    if not (GPIO.input(PIN_BUTTON)):
        time.sleep(0.1)
        if not (GPIO.input(PIN_BUTTON)):
            return 1
    return 0

def run():
    print("start")
    config = get_config()
    pygame.init()
    # Start the signal_hook function in a separate thread
    thread = threading.Thread(target=signal_hook)
    thread.start()
    screen = pygame.display.set_mode((config["width"], config["height"]), 0, 0)
    qr_img = load_image(config["qr_path"])

    screen.fill(color=(255, 255, 255))
    display_text(screen, "Kamera is breit!", color=(20, 230, 20))
    pygame.display.update()

    while 1:
        LOGGER.info("Starting...")
        while 1:
            #display_qr(screen, qr_img)
            

           
            while buttonPressed() == 0:
                 time.sleep(0.05)
                
            photo_path = get_file_name(prefix=config["photo_prefix"], path=config["photo_folder"])

            LOGGER.info(photo_path)
            print(photo_path)
            # Capture photo
            try:
                subprocess.run(
                    [
                        "gphoto2",
                        "--capture-image-and-download",
                        "--camera='Canon EOS 350D (normal mode)'",
                        "--filename={0}".format(photo_path),
                        "--force-overwrite",
                    ]
                )
            except:
                LOGGER.info("Failed to capture image.")
                continue

            try:
                img = load_image(photo_path)
                display_image(screen, img, config["width"], config["height"])
                display_text(
                    screen, "Zuerst das Vergnügen, dann der Upload in die cloud...", size=50
                )
                pygame.display.update()

            except:
                LOGGER.info("Failed to display image.")
                print("Failled to display image")
                
            
            #display_qr(screen, qr_img)

            try:
                display_image(screen, img, config["width"], config["height"])
                uploader.sync_photo2(photo_path=photo_path)
            except:
                print("Failled to upload image")
            

if __name__ == "__main__":
    run()