# -*- coding: utf-8 -*-
"""
/***************************************************************************
 Owner
                                 A QGIS plugin
 wide are mapping
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                             -------------------
        begin                : 2020-11-13
        git sha              : $Format:%H$
        copyright            : (C) 2020 by forschung@ciss.de
        email                : forschung@ciss.de
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/
"""
from itertools import count
from weissflaechenkartierung.src.logger import Logger


class Owner:
    """
    class which holds information about the owners csv file
    """
    _ids = count(0)

    def __init__(self, dictionary):
        if isinstance(dictionary, dict):
            for k, v in dictionary.items():
                if k is None:
                    continue
                if v is None:
                    v = ""
                setattr(self, k, v)
                self.id = next(self._ids)

    @staticmethod
    def from_csv_to_dict(file_name: str = "", column_name: str = "") -> dict:
        """
        returns a dict which contains the owner objects as a dict
        """
        if column_name == "":
            Logger.error("from_csv_to_dict column_name is empty", )
            Logger.data("result: " + str({}), )
            return {}

        import csv
        import chardet
        with open(file_name, 'rb') as file:
            encoding_result = chardet.detect(file.read())

        obj_cts: dict = {}
        with open(file_name, mode='r', encoding=encoding_result['encoding']) as csv_file:
            dict_reader = csv.DictReader(csv_file, delimiter=';')
            for row in dict_reader:
                # create owner object
                try:
                    owner_obj = Owner(dictionary=row)
                except Exception as e:
                    Logger.error("unexpected error " + str(repr(e)), )
                    Logger.error("current row" + str(row), )
                    continue

                try:
                    searched_member = getattr(owner_obj, column_name)
                except AttributeError:
                    Logger.error("AttributeError " + str(repr(column_name)), )
                    Logger.error("Current row " + str(row), )
                    continue

                if searched_member in obj_cts:
                    obj_cts[searched_member].append(owner_obj)
                else:
                    obj_cts[searched_member] = [owner_obj]

        Logger.data("result: " + str(obj_cts), )
        return obj_cts
