'''
/***************************************************************************
Name       :  logging_utilities.py
Description:  Logging Utility Functions for FEWSTools plugin,
              updated from QGIS2
copyright  :  (C) 2022-2023 by FEWS
email      :  jhowton@contractor.usgs.gov
Created    :  12/30/2022 - jhowton
Modified   :
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 ***************************************************************************/
'''
import os
from datetime import datetime

from qgis.core import QgsProject, QgsMessageLog, Qgis


def add_log(process, inputs, outputs):
    '''
    A function to add a log to the layer notes and write a log file.

    params(string) - process - A string for the process given
    params(list) - inputs - A list of inputs to be added to the log message
    params(list) - outputs - A list of outputs to be added to the log message
    '''

    dash_string = "--------------------------------"

    log_message = dash_string + "\n" + process + "\n" + dash_string + "\n\n"

    for in_file in inputs:
        log_message += "Input: " + in_file + "\n"

    log_message += "\n"

    for out_file in outputs:
        if out_file != "":
            log_message += "Output: " + out_file + "\n"

    for out_file in outputs:
        layer_name = os.path.splitext(os.path.basename(out_file))[0]

        # If the layer is displayed, then add the note
        if QgsProject.instance().mapLayersByName(layer_name) != []:
            QgsProject.instance().mapLayersByName(layer_name)[
                0].setCustomProperty('userNotes', log_message)

    now = datetime.now()
    log_path = os.path.join(os.path.split(outputs[0])[
                            0], "Log " + process +
                                now.strftime(" %d.%m.%Y.%H.%M.%S" + ".txt"))

    f_obj = open(log_path, "w")
    f_obj.write(log_message)
    f_obj.close()

    QgsMessageLog.logMessage("Writing log to: " + log_path, level=Qgis.Info)


def log_string(label, in_list):
    '''
    Function to concatenate lists to a label and skip empty lists

    params(string) - label - A string to prefix the given list
    params(list) - in_list - A list of things to be converted to strings
                             and added to the label input
    '''
    out_list = []

    if in_list != []:
        out_list = [label + ": " + ', '.join(str(x) for x in in_list)]

    return out_list
