
import os
import pandas as pd
from collections import defaultdict

def MakeDf(CsvPath):
    # print('MakeDf')
    WhgDf = pd.read_csv(CsvPath)
    a = WhgDf.columns.values.tolist()
    # print(a)
    # print("------------")
    return(WhgDf)


def MakeFlatId(row, Gebäude_ID, Treppenhaus_ID, Einheit_ID):
    # print('MakeFlatId')
    flatID = '_'.join(
        (
            str(row[Gebäude_ID]), 
            str(row[Treppenhaus_ID]), 
            str(row[Einheit_ID])
        )
        )
    # print('flatID: ',flatID)
    # print("------------")
    return flatID

def SortFlats(df, Nutzungstyp, Teilbereich_ID, Gebäude_ID, Treppenhaus_ID, Einheit_ID):
    # print('SortFlats')
    
    dict_flatIDs = defaultdict(list)

    for index, row in df.iterrows():
        if row[Nutzungstyp] == 'WOH':
            if Teilbereich_ID != '-':
                flatType = row[Teilbereich_ID]
            else:
                flatType = "not def"
            
            print("flatType :", flatType)
            
            flatID = MakeFlatId(row, Gebäude_ID, Treppenhaus_ID, Einheit_ID)

            if flatID not in dict_flatIDs[flatType]:
                dict_flatIDs[flatType].append(flatID)
                print('flatID {} added to {}'.format(flatID, flatType))
            else:
                print('flatID {} already present in {}. Added to Maisonette.'.format(flatID, flatType))
                dict_flatIDs['maisonette'].append(flatID)
        
    print("------------")
    return(dict_flatIDs)


def CountFlats(dict_Flats):
    print('CountFlats')
    for k, v in dict_Flats.items():
        # print(k, v)
        print(k, len(v))        
    print('maisonette', dict_Flats['maisonette'])

    print("------------")

def main(Nutzungstyp, Teilbereich_ID, Gebäude_ID, Treppenhaus_ID, Einheit_ID):
    df = MakeDf(CsvPath)
    dict_flatIDs = SortFlats(df, Nutzungstyp, Teilbereich_ID, Gebäude_ID, Treppenhaus_ID, Einheit_ID)
    CountFlats(dict_flatIDs)

if __name__ == "__main__":
    # CsvPath = r"CSV_Files/200527-BDE-NUM-150.csv"

    # cwd = os.getcwd()
    # CsvPath = r"PythonScripts/CSV_Files/TestWhg.csv"
    # CsvPath = os.path.join(cwd, CsvPath)

    CsvPath = r"W:\4258_SwisscantoInvest_DSA_Harsplen_Witikon\4258_06_auswertungen\04_Phase_01_Ueberarbeitung\01_ASA\in_Tabelle\200602-ASA-NUM.csv"
    
    
    # CsvPath = r"W:\4258_SwisscantoInvest_DSA_Harsplen_Witikon\4258_06_auswertungen\04_Phase_01_Ueberarbeitung\02-BDE\Excel-out\200602-BDE-NUM-150.csv"
    
    # cwd = os.getcwd()
    # CsvPath = r"PythonScripts/CSV_Files/200602-BDE-NUM-160.csv"
    # CsvPath = os.path.join(cwd, CsvPath)
    # print(CsvPath)

    Teilbereich_ID = "Teilbereich_ID"

    Nutzungstyp = "Nutzungstyp"
    Gebäude_ID = "Gebäude_ID"
    Treppenhaus_ID = "Treppenhaus_ID"
    Einheit_ID = "Einheit_ID"
    
    main(Nutzungstyp, Teilbereich_ID, Gebäude_ID, Treppenhaus_ID, Einheit_ID)