# Funktionen bzgl. Timestamps

import time
import datetime
import os
from definitions import *

# Zeitstempel schreiben
def append_timestamp(filename):
    # Hole den aktuellen Timestamp in Epoch-Zeit
    timestamp = int(time.time())

    try:
        # Öffne die Datei im Anhang-Modus ('a')
        with open(filename, 'a') as file:
            # Schreibe den Timestamp in die Datei und füge einen Zeilenumbruch hinzu
            file.write(f"{timestamp}\n")
        file.close()
    except FileNotFoundError:
        # Fehlende Verzeichnisse anlegen
        folder_path = os.path.dirname(filename)
        os.makedirs(folder_path, exist_ok=True)
        append_timestamp(filename)

# Anzahl der Zeilen zählen
def len_timestamps(filename):
    try:
        # Öffne die Datei im Lese-Modus ('r')
        with open(filename, 'r') as file:
            # Zähle die Zeilen
            lines = file.readlines()
        file.close()
        print(len(lines))
        return len(lines)
    except FileNotFoundError:
        print(f"Die Datei {filename} wurde nicht gefunden.")
        return 0

# Stempelzustand auslesen
def stempel_zustand(filename):
    lines = len_timestamps(filename)
    if lines == 0:
        print(f"Keine Einträge")
    elif lines % 2 == 0:
        return(status_out)
    else:
        return(status_in)

# Letzten Zeitstempel auswerten
def get_last_2_timestmaps(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
    file.close()
    second_last_line = lines[-2]
    last_line = lines[-1]
    last_2_timestmaps = [second_last_line, last_line]
    return last_2_timestmaps

# Stempelübersicht zusammenstellen
def overview(filename):

    # Öffne die Datei im Lese-Modus ('r')
    with open(filename, 'r') as file:
        lines = file.readlines()

    timelist = [[] for i in range(3)]

    for i in range(0, len(lines)):
        if (i + 1) % 2 == 0:
            timelist[1].append(lines[i])
        else:
            timelist[0].append(lines[i])
    if len(timelist[0]) > len(timelist[1]):
        timelist[1].append("")

    for i in range(0, len(timelist[0])):
        timelist[2].append(int(timelist[1][i])-int(timelist[0][i]))

    for i in range(0, len(timelist[0])):
        print(convert_timestamp(timelist[0][i], "%d.%m.%Y %H:%M") + " - " + convert_timestamp(timelist[1][i], "%d.%m.%Y %H:%M") + " Dauer: " + convert_duration(timelist[2][i]))

# Timestamp konvertieren
def convert_timestamp(timestamp, format):
    try:
        return str(datetime.datetime.fromtimestamp(int(timestamp)).strftime(format))
    except:
        return ("...")

#Zeitdauerdarstellung berechnen
def convert_duration(duration):
    hours = int(duration / 3600)
    minutes = int((duration - hours * 3600)  / 60)
    seconds = int(duration - hours * 3600 - minutes * 60)

    return(f"{hours:02d}" + ":" + f"{minutes:02d}" + ":" + f"{seconds:02d}")