import os
import csv
import tkinter as tk
from tkinter import filedialog

# Open a folder selection dialogue and get the folder path
root = tk.Tk()
root.withdraw()
folder_selected = filedialog.askdirectory()

# Open the CSV file for writing
with open('output.csv', 'w', newline='', encoding='utf-8') as csvfile:
    csvwriter = csv.writer(csvfile, delimiter=';')
    csvwriter.writerow(['AGEF', 'AGEM', 'AGEACC', 'COUPLE', 'EVENT', 'NUM_VISITORS', 'DIST'])
    
    # Loop through all files in the selected folder
    for filename in os.listdir(folder_selected):
        file_path = os.path.join(folder_selected, filename)
        
        # Convert filename to lowercase for case-insensitive comparison
        filename_lower = filename.lower()
        
        # Determine the file type and EVENT
        if filename_lower.endswith("women.s-exp.txt"):
            file_type = 0
            event = filename.split(" ")[0].upper()
        elif filename_lower.startswith("p-") and (filename_lower.endswith("couple.c-exp.txt") or filename_lower.endswith("couples.c-exp.txt")):
            file_type = 1
            event = filename.split(" ")[0][2:].upper()
        elif filename_lower.endswith("men.s-exp.txt"):
            file_type = 2
            event = filename.split(" ")[0].upper()
        elif filename_lower.startswith("p-") and (filename_lower.endswith("couple.s-exp.txt") or filename_lower.endswith("couples.s-exp.txt")):
            file_type = 3
            event = filename.split(" ")[0][2:].upper()
        else:
            continue  # Skip other files
        
        # Open the text file and read data
        with open(file_path, 'r', encoding='utf-8') as f:
            lines = f.readlines()
            for line in lines:
                parts = line.strip().split("\t")
                agef, agem, ageacc, couple, num_visitors, dist = '', '', '', file_type, '', parts[-1]
                
                if file_type in [0, 2]:
                    num_visitors = 1
                    if file_type == 0:
                        agef = parts[0]
                    else:
                        agem = parts[0]
                elif file_type in [1, 3]:
                    num_visitors = 2
                    if file_type == 1:
                        agef, agem = parts[0], parts[1]
                    else:
                        ageacc = parts[0]
                
                if dist == '-1':
                    dist = ''
                csvwriter.writerow([agef, agem, ageacc, couple, event, num_visitors, dist])
