# Zeiterfassung

# User bezogene Funktionen

import os
import datetime
import time
import json

from definitions import userfolder, scriptpath, usersettingsfilename, photofilename, status_in, status_out

# Benutzerklasse

class user:
    def __init__(self, name):
        self.userfolder =  f"{scriptpath}/{userfolder}/{name}"
        self.settingsfile = f"{self.userfolder}/{usersettingsfilename}"
        self.photofile = f"{self.userfolder}/{photofilename}"

        # Stammdaten einlesen
        try:
            with open(self.settingsfile) as json_file:
                data = json.load(json_file)
            json_file.close()
        except:
            pass
            #Hier muss noch Fehlerbehandlungcode hin

        self.fullname = data["name"]
        self.password = data["password"]
        self.workhours = data["workhours"]

    def get_stamp_file(self):
        year = str(datetime.datetime.now().year)
        month = str(datetime.datetime.now().month)
        completepath = f"{self.userfolder}/{year}-{month}.txt"
        return completepath

    def timestamp(self):
        filename = self.get_stamp_file()
        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)
            self.timestamp()

    def stamp_status(self):
        try:
            # Öffne die Datei im Lese-Modus ('r')
            with open(self.get_stamp_file(), 'r') as file:
                # Zähle die Zeilen
                lines = file.readlines()
            file.close()
        except FileNotFoundError:
            print(f"Die Datei {filename} wurde nicht gefunden.")
        if len(lines)== 0:
            print(f"Keine Einträge")
        elif len(lines) % 2 == 0:
            return (status_out)
        else:
            return (status_in)

    def last_2_timestmaps(self):

        with open(self.get_stamp_file(), 'r') as file:
            lines = file.readlines()
        file.close()

        if len(lines) > 2:
            second_last_line = int(lines[-2])
            last_line = int(lines[-1])
            last_2_timestmaps = [second_last_line, last_line]
            return last_2_timestmaps

        elif len(lines) == 1:
            return int(lines[0])
        else:
            return -1

# Benutzer auflisten
def list_users():
    users = [d for d in os.listdir(userfolder) if os.path.isdir(os.path.join(userfolder, d))]
    return users

