import os
from configparser import ConfigParser
from glob import glob
import csv

fieldnames = [
    "codice_ricetta",
    "cliente",
    "codice_prodotto",
    "descrizione",
    "prova_tenuta_abilitata_2"
]

# FOLDER CONFIGURATION
in_path="../../tmp/ricette/"
files=glob(f"{in_path}/**/*.dsg",recursive=True)
csv_path="../test/csv_import/importazione da banco montaggio.csv"
data=[]

#FOR EACH FILE CREATE A TEST RECIPE
for file in files:
    print(f"READING {file}")
    config = ConfigParser(allow_no_value=True)
    config.optionxform = str
    read = config.read(file)
    read_values=dict(config._sections)
    read_values= {key.lower():val for key,val in read_values.items()}
    line={
        "codice_ricetta":list(read_values["numero disegno"].keys())[0],
        "cliente":list(read_values["cliente"].keys())[0],
        "codice_prodotto":list(read_values["numero disegno"].keys())[0],
        "descrizione":os.path.basename(file),
        "prova_tenuta_abilitata_2":"x" if list(read_values["prova2:tempo di riempimento"].keys())[0] not in ("0","00") else ""

    }
    data.append(line)

# SAVE RECIPES TO CSV FILE
with open(csv_path, "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames, extrasaction="ignore")
    w.writeheader()
    w.writerows(data)

print(f"IMPORTED {len(files)} FILES")