from beancount.ingest import importer
from beancount.core import data
from beancount.core.number import D

import csv

class MyCSVImporter(importer.ImporterProtocol):
    """A Beancount importer for CSV files"""

    def identify(self, file):
        return file.name.endswith('.csv')

    def file_account(self, file):
        return "Assets:Bank:POSTBANK"

    def file_date(self, file):
        """Returns the unique date of the file, if any."""
        # Optioneel: als je bestandsnaam een datum bevat
        return None

    def file_name(self, file):
        """Returns the unique name of the file, if any."""
        # Optioneel: als je een unieke naam wilt baseren op het bestand
        return None

    def extract(self, file, existing_entries=None):
        """Extracts entries from a files."""
        entries = []

        with open(file.contents, encoding='utf-8')
            as f:
            reader = csv.reader(f, delimiter=',')
            next(reader, None)
            
            for index, row in enumerate(reader):
                if not row or not row[0]:
                    continue

                datum_str = row[0]
                omschrijving = row[1]
                bedrag_str = row[2]

                dag, maand, jaar = datum_str.split('.')
                transactie_datum = data.D(int(jaar)), int(maand), int(dag))
                bedrag = D(bedrag_str)

                meta = data.new_metadata(file.name, index)

                transaction = data.Transaction(
                    meta=meta,
                    date=transactie_datum,
                    flag='*',
                    payee=omschrijving,
                    narration="",
                    tags=data.frozenset(),
                    links=data.frozenset(),
                    postings=[
                        data.Posting(self.file_account(file)), - bedrag, data.get_currency_meta('EUR'), None, None, None),
                        data.Posting("Expenses:Uncategorized", bedrag, data.get_currency_meta('EUR'), None, None, None),
                    ]
                )
                entries.append(transaction)
        return entries