#!/usr/bin/env python3

import time
from PIL import Image, ImageDraw
import lib.display
import locale
locale.setlocale(locale.LC_ALL, "de_DE.UTF-8")

# Replace with your free Finnhub API key
API_KEY = "d3t8099r01qigeg1s7cgd3t8099r01qigeg1s7d0"
import finnhub
finnhub_client = finnhub.Client(api_key="d3t8099r01qigeg1s7cgd3t8099r01qigeg1s7d0")

def get_bitcoin_price():
    symbol = "BINANCE:BTCEUR"
    data = finnhub_client.quote(symbol)
    #print("getting finnhub")
    return data['c']

def start(stop_event, args):
  last_price = None
  trend = None
  image_buffer = lib.display.matrix.buffer()
  draw = ImageDraw.Draw(image_buffer)
  symbol = '-'
  color = (255,255,255)

  while not stop_event.is_set():
    # All to black
    draw.rectangle( ((0,0),(lib.display.matrix.width-1,lib.display.matrix.height-1)), fill=(0,0,0) )

    price = get_bitcoin_price()
    price_str = locale.format_string("%d", price, grouping=True)

    # Trend berechnen
    if last_price:
      if price > last_price:
        trend = 1
        symbol = "▴"
        color = (0, 255, 0)
      elif price < last_price:
        trend = -1
        symbol = "▾"
        color = (255, 0, 0)

    text = f"{symbol} BTC: {price_str}€"
    #text = f"BTC: {price:.0f}€"

    draw.text((10, 0), text, fill=color, font=lib.display.matrix.large_font)

    lib.display.matrix.show(image_buffer)

    last_price = price
    # Alle 10 Sekunden einen neuen Kurs holen. Jede Sekunde auf "stop" horchen.
    for i in range(1,10):
      if stop_event.is_set():
        return

      time.sleep(1)

