# -*- coding: utf-8 -*-
"""
/***************************************************************************
 GenerateSwmmInp
                                 A QGIS plugin
 This plugin generates SWMM Input files
 Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
                              -------------------
        begin                : 2021-07-09
        copyright            : (C) 2021 by Jannik Schilling
        email                : jannik.schilling@posteo.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.                                   *
 *                                                                         *
 ***************************************************************************/
"""
__author__ = 'Jannik Schilling'
__date__ = '2023-05-09'
__copyright__ = '(C) 2021 by Jannik Schilling'


import pandas as pd
import numpy as np


def fill_landuse_params(
        df,
        pollutant_names,
        landuses_names,
        b_w
    ):
    '''
    fills buildup or washoff data frames if missing
    :param pd.DataFrame df
    :param list pollutant_names
    :param list landuses_names
    :param str b_w: "b" or "w"
    :return: pd.DataFrame
    '''
    missing = []
    for l_n in landuses_names:
        df_sub = df[df['Name'] == l_n]
        if b_w == 'b':
            missing = missing + [[l_n, p_n, 'NONE', 0, 0, 0, 'AREA'] for p_n in pollutant_names if p_n not in df_sub['Pollutant'].to_list()]
        if b_w == 'w':
            missing = missing + [[l_n, p_n, 'NONE', 0, 0, 0, 0] for p_n in pollutant_names if p_n not in df_sub['Pollutant'].to_list()]
    if len(missing) == 0:
        pass  # returns None
    else:
        missing_df = pd.DataFrame(missing)
        missing_df.columns = df.columns
        return missing_df


def get_quality_params_from_table(
        quality_raw_dict,
        all_subcatchments
    ):
    """
    generates a dictionary with quality data from an excel file
    :param dict quality_raw_dict
    :param list all_subcatchments
    """
    quality_params = ['POLLUTANTS', 'LANDUSES', 'COVERAGES', 'LOADINGS']
    for q_p in quality_params:
        q_df_raw = quality_raw_dict[q_p]
        if q_p == 'POLLUTANTS':
            pollutants_df = q_df_raw[[
                'Name',
                'Units',
                'RainConcentr',
                'GwConcentr',
                'IiConcentr',
                'DecayCoeff',
                'SnowOnly',
                'CoPollutant',
                'CoFraction',
                'DwfConcentr',
                'InitConcetr'
            ]]
            pollutants_df = pollutants_df[pollutants_df['Name'] != '']
            pollutants_df = pollutants_df[pd.notna(pollutants_df['Name'])]
            pollutant_names = pollutants_df['Name'].to_list()  # names of pollutants for fill function
            pollutants_df = pollutants_df.fillna('*')
        if q_p == 'LANDUSES':
            q_df_raw = q_df_raw[q_df_raw['Name'] != ";"]
            landuses_df = q_df_raw[[
                'Name',
                'SweepingInterval',
                'SweepingFractionAvailable',
                'LastSwept'
            ]].drop_duplicates()
            landuses_df = landuses_df[pd.notna(landuses_df['Name'])]
            landuses_names = landuses_df['Name'].drop_duplicates().to_list()  # names of land uses for fill function
            landuses_df = landuses_df.reset_index(drop=True)
            buildup_df = q_df_raw[[
                'Name',
                'Pollutant',
                'BuildupFunction',
                'BuildupMax',
                'BuildupRateConstant',
                'BuildupExponent_SatConst',
                'BuildupPerUnit'
            ]]
            buildup_df = pd.concat(
                [
                    buildup_df,
                    fill_landuse_params(
                        buildup_df,
                        pollutant_names,
                        landuses_names,
                        'b'
                    )
                ]
            )
            washoff_df = q_df_raw[[
                'Name',
                'Pollutant',
                'WashoffFunction',
                'WashoffpCoefficient',
                'WashoffExponenet',
                'WashoffCleaninfEfficiency',
                'WashoffBmpEfficiency'
            ]]
            washoff_df = pd.concat(
                [
                    washoff_df,
                    fill_landuse_params(
                        washoff_df,
                        pollutant_names,
                        landuses_names,
                        'w'
                    )
                ]
            )
        if q_p == 'COVERAGES':
            coverages_df = q_df_raw[q_df_raw['Subcatchment'] != ';']
            coverages_df = coverages_df[[
                'Subcatchment',
                'Landuse',
                'Percent'
            ]]
            # reduce to those, which are actually needed for the subcatchments
            coverages_df = coverages_df[
                coverages_df['Subcatchment'].isin(all_subcatchments)
            ]
        if q_p == 'LOADINGS':
            loadings_df = q_df_raw
            loadings_df = loadings_df[[
                'Subcatchment',
                'Pollutant',
                'InitialBuildup'
            ]]
    return (
        pollutants_df,
        landuses_df,
        buildup_df,
        washoff_df,
        coverages_df,
        loadings_df
    )