#' @title Ecriture des résultats dans Excel avec taux de croissance annuels et
#' possibilité d'inclure des colonnes du tableau des mesures.
#'
#' @description Ecriture des résultats dans Excel avec taux de croissance annuels
#' et possibilité d'inclure des colonnes du tableau des mesures.
#'
#' @param PARAM_GLOBAL a single row data frame, of which we use the following
#'   parameters:
#'   - `path_ahvoutput`  : post_process path of the container
#'   (paste0(path_post_process, "/")), see function
#'   \code{\link{wrap_ahv_postprocessing}}
#'   - `file_ahvoutput`  : name of the xlsx file of FH_AHV (FH_AHV.xlsx)
#'   - `jahr_abr`        : Jahr Abrechnung
#'   - `jahr_lastoutput` : Dernière année de publication de la projection
#'   - `spaltenidx`: liste des colonnes à écrire dans le fichier Excel sous la
#'    forme d'indices.
#'   - `spaltenmio`: liste des colonnes à écrire dans le fichier Excel en millions
#'   de francs.
#'
#' @param diskont Dummy pour actualiser les chiffres.
#'
#' @param AHV_FHH data frame containing the full fhh-ahv, see function
#' \code{\link{mod_ahv_postprocessing}}.
#'
#' @param ECKWERTE_SCENARIO data frame containing the eckwerte of the current
#'   scenario, see function \code{\link{mod_eckwerte}}.
#'
#' @param ECKWERTE_EXTENDED data frame containing the eckwerte extended in case
#' of shocks occurring later (in a long term perspective), see function
#' \code{\link{mod_eckwerte}}.
#'
#' @param PARAM_ALL Data frame containing all the parameters for the actual run,
#' see functions \code{\link{parsimonify_param}}.
#'
#' @param path_out_identifier nom unique pour le path_out
#'
#' @return a `tidylist` containing the following tidy data frames:
#'   - `AUSGABE`
#'
#' @author [MAS BSV](mailto:sekretariat.mas@bsv.admin.ch)
#'
#' @export

#
write_file_ahv_fhh_flexible <- function(PARAM_GLOBAL,
                                        AHV_FHH,
                                        ECKWERTE_SCENARIO,
                                        ECKWERTE_EXTENDED,
                                        PARAM_ALL,
                                        path_out_identifier,
                                        diskont) {
    
    
    # --- Spalten und Sprache definieren -----------------------------------------
    if (diskont) {
        path_out_file <- file.path(
            path_out_identifier, "post_process", PARAM_GLOBAL$file_ahvoutput
        )
        if(!dir.exists(dirname(path_out_file))) {
            dir.create(dirname(path_out_file))
        }
    } else {
        path_out_file <- file.path(
            path_out_identifier, "post_process", "FH_AHV_nom.xlsx"
        )
        if(!dir.exists(dirname(path_out_file))) {
            dir.create(dirname(path_out_file))
        }
    }
    
  if ("jahr_start_fhh" %in% names(PARAM_GLOBAL)){
    if (!is.null(PARAM_GLOBAL$jahr_start_fhh)){
    # Join the AHV_FHH
    AHV_OUT <- AHV_FHH %>%
        filter(jahr %in%
                   c(PARAM_GLOBAL$jahr_start_fhh:PARAM_GLOBAL$jahr_lastoutput))
    }else{
      AHV_OUT <- AHV_FHH %>%
        filter(jahr %in%
                 c(PARAM_GLOBAL$jahr_abr:PARAM_GLOBAL$jahr_lastoutput))  
    }}else{
      AHV_OUT <- AHV_FHH %>%
        filter(jahr %in%
                 c(PARAM_GLOBAL$jahr_abr:PARAM_GLOBAL$jahr_lastoutput))  
      
    }
    
    # Liste des colonnes à écrire dans le fichier excel (soit par le paramètre
    # spaltenmio de PARAM_GLOBAL, soit avec les noms écrits ci-dessous) en millions
    # de francs.
    if ("spaltenmio" %in% colnames(PARAM_GLOBAL) == FALSE) {
        spaltenmio <- c(
            "aus_tot",
            "btr_vs_ag", "btr_mwst", "btr_bund", "btr_uebr",
            "ein_total", "erg_umlag", "kap_etr", "erg_betr", "kap", "kap_oiv"
        )
    } else {
        spaltenmio <- separate_at_comma(PARAM_GLOBAL$spaltenmio)
    }
    
    # Liste des colonnes à écrire dans le fichier excel (soit par le paramètre
    # spaltenidx de PARAM_GLOBAL, soit avec les noms écrits ci-dessous) sous la
    # forme d'indices.
    if ("spaltenidx" %in% colnames(PARAM_GLOBAL) == FALSE) {
        spaltenidx <- c(
            "indx_ausg_ls", "indx_uml_mwst", "indx_uml_ls", "indx_bed_mwst",
            "indx_bed_ls", "indx_kap_ausg", "indx_kap_oiv_ausg"
        )
    } else {
        spaltenidx <- separate_at_comma(PARAM_GLOBAL$spaltenidx)
        if("indx_ersq" %in% spaltenidx){
            spaltenidx <- spaltenidx[spaltenidx != "indx_ersq"]
        }
    }
    
    # Retrouver les colonnes désirées dans AHV_OUT
    spaltenmio <- intersect(spaltenmio, colnames(AHV_OUT))
    spaltenidx <- intersect(spaltenidx, colnames(AHV_OUT))
    
    # --- Bearbeitung der Daten --------------------------------------------------
    AUSGABE <- AHV_OUT %>%
        dplyr::select(jahr, !!spaltenmio, !!spaltenidx)
    
    wb <- createWorkbook()
    
    ans <- lapply(
        c("d", "f", "i"),
        write_sheet_go_simplified,
        wb = wb,
        AUSGABE = AUSGABE,
        PARAM_GLOBAL = PARAM_GLOBAL,
        PARAM_ALL = PARAM_ALL,
        ECKWERTE_SCENARIO = ECKWERTE_SCENARIO,
        ECKWERTE_EXTENDED = ECKWERTE_EXTENDED,
        diskont
    )
    
    # --- Save -------------------------------------------------------------------
    
    # openXL(wb)
    saveWorkbook(wb, path_out_file, overwrite = TRUE)
    
    # either return value or side effect, but not both
    return(TRUE)
}
