#' @title Fonction pour écrire la worksheet dans chacune des langues.
#'
#' @description Fonction pour écrire la worksheet dans chacune des langues.
#'
#' @param wb workbook
#' @param ws worksheet
#' @param DATA données à écrire dans le fichier Excel
#' @param ECKWERTE valeurs macroéconomiques à écrire dans le fichier Excel
#' @param main.title titre dans la langue sélectionnée
#' @param main.subtitle sous-titre dans la langue sélectionnée
#' @param topnote.left units.text
#' @param topnote.right stand.abrechnung
#' @param endnote.top bsv.version
#' @param endnote.left footnote.rentenanpassung
#' @param endnote.right footnote.demographie
#' @param endnote.bottom c(intern.output.feature, footnote.note1, footnote.note2)
#' @param title.footnotes titre des footnotes dans la langue sélectionnée
#' @param title.eckwerte titre des Eckwerte dans la langue sélectionnée
#' @param title.jahre.eckwerte titre des années des Eckwerte dans la langue sélectionnée
#' @param footnotes.extra footnote pour valeurs escomptés ou pas
#' @param bold.year.output doit être NULL
#' @param meta_cnames noms des colonnes désirées (pogrammées dans text_main.csv et
#' dans PARAM_GLOBAL avec cols_with_pc, spaltenmio et spaltenidx).
#' @param description.qr texte de la description à imprimer dans le code QR.
#' @param diskont dummy: si TRUE, la version imprimée est escomptée.
#' @param hard.round doit être FALSE
#' @param PARAM_GLOBAL a single row data frame, of which we use the following
#'   parameters:
#'   - `bold_year_output`: année dont la ligne doit être imprimée en gras.
#'   - `jahr_lastoutput`: dernière année dont la ligne doit être imprimée.
#'
#' @author [MAS BSV](mailto:sekretariat.mas@bsv.admin.ch)
#'
#' @export


write_sheet <- function(wb,
                        ws,
                        DATA,
                        ECKWERTE,
                        main.title,
                        main.subtitle,
                        topnote.left,
                        topnote.right,
                        endnote.top,
                        endnote.left,
                        endnote.right,
                        title.footnotes,
                        title.eckwerte,
                        title.jahre.eckwerte,
                        bold.year.output = NULL,
                        meta_cnames,
                        diskont,
                        hard.round = FALSE,
                        explication.shade = explication.shade,
                        PARAM_GLOBAL
                        # formul.RR,
                        # formul.RC,
                        # formul.RE,
                        # formul.C
                        ) {
    
    # Row where to begin
    first_year <- min(DATA$jahr)
    last_year <- max(DATA$jahr)
    last_year_row <- 11 + last_year - first_year
    
    # Number of rows to move down because of the subtitle
    if (main.subtitle != "") {
        value_st <- 1
    } else {
        value_st <- 0
    }
    
    # init worksheet -------------------------------------------------------------
    addWorksheet(wb, ws)
    
    # General Formatting
    modifyBaseFont(wb, fontSize = 9)
    # micro-rows
    setRowHeights(wb, sheet = ws, rows = (c(4, 6, 10, last_year_row + c(1, 2, 4)) + value_st), heights = 5)
    # wide header rows
    setRowHeights(wb, sheet = ws, rows = (c(5, 7) + value_st), heights = c(40, 85))
    # 5row-block
    first_of_block <-
        tibble(year = first_year:last_year, row = 11:last_year_row) %>%
        mutate(first_of_block = (year %% 5) == 1) %>%
        filter(first_of_block) %>%
        pull(row)
    
    setRowHeights(wb, sheet = ws, rows = (first_of_block + value_st), heights = 17)
    
    
    # Add data ---------------------------------------------------------------------
    global_col_count <- 1
    global_footnotes <- tibble(index = integer(0), text = character(0))
    
    add_data_block <- function(dta, main, title, footnote = NULL, value_st) {
        stopifnot(last_year_row - 11 + 1 == nrow(dta))
        
        col_last <- global_col_count + ncol(dta) - 1
        col_range <- global_col_count:col_last
        
        # ideally, we use a clean prefix scheme to determine the formating
        col_range_pct0 <- col_range[grepl("^indx_kap", names(dta))]
        col_range_pct1 <- col_range[grepl("^indx_", names(dta)) & !grepl("^indx_kap", names(dta))]
        col_range_pc <- col_range[grepl("^pc_", names(dta))]
        
        # all others are mio
        col_range_mio <- setdiff(col_range, c(col_range_pct0, col_range_pct1, col_range_pc))
        
        if (hard.round) {
            cols_to_round <- names(dta)[col_range %in% setdiff(col_range_mio, 1)]
            dta <- mutate_at(dta, cols_to_round, function(e) round(e / 1e6))
        }
        
        writeData(wb, ws, rbind(NA, dta, NA), colNames = FALSE, startCol = global_col_count, startRow = (10 + value_st), borders = "surrounding")
        
        if (hard.round) {
            addStyle(wb, ws, style_body_hard, (11:last_year_row + value_st), col_range_mio, gridExpand = TRUE, stack = TRUE)
        } else {
            addStyle(wb, ws, style_body, (11:last_year_row + value_st), col_range_mio, gridExpand = TRUE, stack = TRUE)
        }
        # addStyle(wb, ws, style_body_pct0, (10:last_year_row + value_st), col_range_pct0, gridExpand = TRUE, stack = TRUE)
        
        # non standard col width for data columns
        setColWidths(wb, ws, col_range, widths = 10.5) # 10.5 entspricht 69 px
        # pc column styling
        if (length(col_range_pc) > 0) {
            pc_merge_cols <- lapply(col_range_pc, function(e) c(e - 1, e))
            # small width for pc cols
            setColWidths(wb, ws, col_range_pc, widths = 5.5) # 10.5 entspricht 69 px
            # style for pc cols
            addStyle(wb, ws, percent_style, (11:last_year_row + value_st), col_range_pc, gridExpand = TRUE, stack = TRUE)
            
            # merge pc col titles
            lapply(pc_merge_cols, function(e) mergeCells(wb, ws, cols = e, rows = (7 + value_st)))
        }
        
        # main
        writeData(wb, ws, rbind(NA, NA, as_tibble(as.data.frame(as.list(main))),NA, NA),
                  colNames = FALSE, startCol = global_col_count, startRow = (5 + value_st),
                  borders = "surrounding"
        )
        addStyle(wb, ws, style_main, (7 + value_st), col_range, gridExpand = TRUE, stack = TRUE)
        
        # title
        mergeCells(wb, ws, cols = col_range, rows = (5 + value_st))
        writeData(wb, ws, title, colNames = FALSE, startCol = global_col_count, startRow = (5 + value_st))
        addStyle(wb, ws, style_title, (5 + value_st), global_col_count, stack = TRUE)
        
        # footnote (opt)
        if (!is.null(footnote)) {
            stopifnot(length(footnote) == length(main))
            writeData(wb, ws, as.data.frame(as.list(footnote)),
                      colNames = FALSE, startCol = global_col_count,
                      startRow = 10
            )
            addStyle(wb, ws, style_footnote, 10, col_range, gridExpand = TRUE, stack = TRUE)
        }
        
        global_col_count <<- col_last + 1 # return next iterator value
    }
    
    # ID des variations annuelles en pourcent
    pc_id <- meta_cnames %>%
        filter(grepl("^pc_", id)) %>%
        dplyr::select(id)
    
    order_id <- meta_cnames %>% dplyr::select(id)
    
    # Arrondir à un chiffre après la virgule les pc
    DATA_PC <- round(DATA %>%
                         dplyr::select(pc_id[[1]]) * 100,
                     digits = 1
    )
    
    DATA <- DATA %>%
        dplyr::select(-pc_id[[1]]) %>%
        bind_cols(DATA_PC)
    
    DATA <- DATA %>%
        dplyr::select(order_id[[1]])
    
    # add data blocks successively
    for (title in unique(meta_cnames$title)) {
        idx <- which(title == meta_cnames$title)
        dta <- DATA[, idx]
        
        # main
        main <- meta_cnames[idx, ][["main"]]
        
        # footnote
        meta_footnote <- meta_cnames[idx, ][["footnote"]]
        last_footnote <- if (nrow(global_footnotes) > 0) max(global_footnotes$index) else 0L
        
        add_data_block(dta, main = main, title = title, footnote = NULL, value_st = value_st)
    }
    
    last_year_row <- last_year_row + value_st
    
    inside_footnote <- meta_cnames[["footnote"]]
    in_footnote <- tibble(
        index = seq_along(inside_footnote),
        text = inside_footnote
    )
    
    in_footnote <- drop_na(in_footnote)

    fn_nm <- 0 # ohne footnote preisbasis abrechnungsjahr
    for (type_fn in unique(in_footnote$text)) {
        fn_nm <- fn_nm + 1
        for (coll in in_footnote$index[which(in_footnote$text == type_fn)]) {
            writeData(wb, ws, paste("(", fn_nm, ")", sep = ""), coll, (9 + value_st))
            addStyle(wb, ws, nb_foot, cols = coll, rows = (9 + value_st))
        }
    }
    
        text_footnote <- unique(in_footnote$text)
    
    counter <- 0
    counter_row <- 0
    #write footnote on the bottom of the table
    #if for multi row footnot 
    # indique where too cut with -- in the template file
    for (text_fn in text_footnote) {
        if(grepl("--",text_fn)){
        counter <- counter + 1
        counter_row <- counter_row + 1
        multi_row <- strsplit(text_fn, "--")
        for (j in 1:length(multi_row[[1]])) {
            #write a row under if it's not the first line
            if(j == 1){
                writeData(
                    wb, ws, paste(paste("(", counter, ")", sep = ""), multi_row[[1]][j], sep = " "), 1,
                    last_year_row + 4 + counter_row
                )
            }else{
            counter_row = counter_row + 1
            writeData(
                wb, ws, multi_row[[1]][j], 1,
                last_year_row + 4 + counter_row
            )
            }
        }
        }else{
        counter <- counter + 1
        counter_row <- counter_row + 1
        writeData(
            wb, ws, paste(paste("(", counter, ")", sep = ""), text_fn, sep = " "), 1,
            last_year_row + 4 + counter_row
        )
        }
    }
    
    # style year col
    addStyle(wb, ws, style_body_year, 10:last_year_row, 1, stack = TRUE)
    
    if ("bold_year_output" %in% colnames(PARAM_GLOBAL)) {
        addStyle(wb, ws, style_bold, last_year_row - (PARAM_GLOBAL$jahr_lastoutput - PARAM_GLOBAL$bold_year_output),
                 1:50,
                 stack = TRUE
        )
    } else {
        addStyle(wb, ws, style_bold, 21, 1:50, stack = TRUE)
    }
    
    # a smaller col with for year colum
    setColWidths(wb, ws, 1, widths = 7) # 10.5 entspricht 69 px
    
    # Header ---------------------------------------------------------------------
    writeData(wb, ws, main.title)
    addStyle(wb, ws, style_main_title, 1, 1, stack = TRUE)
    
    writeData(wb, ws, main.subtitle, startRow = 2, startCol = 1)
    addStyle(wb, ws, style_subtitle, 2, 1, stack = TRUE)
    
    writeData(wb, ws, topnote.left, startRow = (3 + value_st), startCol = 1)
    
    writeData(wb, ws, topnote.right, startRow = (3 + value_st), startCol = global_col_count - 1)
    addStyle(wb, ws, style_stand_abrechnung, (3 + value_st), global_col_count - 1, stack = TRUE)
    
    # Footer ---------------------------------------------------------------------
    # on small tables, write footnotes below the QR code
    if (global_col_count < 16) {
        footnote_row <- last_year_row + 12
    } else {
        footnote_row <- last_year_row + 3
    }
    writeData(wb, ws, title.footnotes, startRow = footnote_row, startCol = 1)
    addStyle(wb, ws, style_bold, footnote_row, 1, stack = TRUE)
    # writeData(wb, ws, mutate(global_footnotes, text = paste0("(", index, ") ", text))$text, startRow = footnote_row + 2, startCol = 1)
    
    ## shade for value after the limit 
    if(!is.null(PARAM_GLOBAL$year_shade)){
        if(PARAM_GLOBAL$year_shade){
           
           first_jahr_shade <- last_year_row - (PARAM_GLOBAL$jahr_lastoutput-PARAM_GLOBAL$jahr_abr)+PARAM_GLOBAL$year_after_abr_shade+1
           last_jahr_shade <- last_year_row+1
        
           color <- createStyle(fgFill = "#eeeeee")
           addStyle(wb,ws,color,rows = first_jahr_shade:last_jahr_shade,
                    cols = 1:23,stack = TRUE,gridExpand = TRUE)
        }
    }
    
    #explication shade
    if(!is.null(PARAM_GLOBAL$year_shade)){
        if(PARAM_GLOBAL$year_shade){
            
    writeData(wb, ws, explication.shade, startRow = footnote_row + counter_row + 3, startCol = 1)
    addStyle(wb, ws, style_bold, footnote_row + counter_row + 3, 1, stack = TRUE)
        }}
    
    
    # footer right
    writeData(wb, ws, title.eckwerte, startRow = last_year_row + 3, startCol = (global_col_count - ncol(ECKWERTE) - 1))
    addStyle(wb, ws, style_bold, last_year_row + 3, (global_col_count - ncol(ECKWERTE) - 1), stack = TRUE)
    
    writeData(wb, ws, endnote.top, startRow = last_year_row + 12, startCol = global_col_count - 1)
    addStyle(wb, ws, style_bsv_version, last_year_row + 12, global_col_count - 1, stack = TRUE)
    
    writeData(wb, ws, endnote.left, startRow = last_year_row + 8, startCol = (global_col_count - ncol(ECKWERTE) - 1))
    addStyle(wb, ws, style_italic, last_year_row + 8, (global_col_count - ncol(ECKWERTE) - 1), stack = TRUE)
    
    # writeData(wb, ws, endnote.right, startRow = last_year_row + 10, startCol = global_col_count - 1)
    # addStyle(wb, ws, style_italic_right, last_year_row + 10, global_col_count - 1, stack = TRUE)
    endnote.right.split <- strsplit(endnote.right, " : ")
    writeData(wb, ws, paste0(endnote.right.split[[1]], " :"), startRow = last_year_row + 10, startCol = global_col_count - ncol(ECKWERTE)- 1)
    addStyle(wb, ws, style_bold, last_year_row + 10, global_col_count - ncol(ECKWERTE) - 1, stack = TRUE)
    
    writeData(wb, ws, endnote.right.split[[1]][2], startRow = last_year_row + 11, startCol = global_col_count -ncol(ECKWERTE) - 1)

    
    writeData(wb, ws, c(title.jahre.eckwerte, ECKWERTE$main),
              colNames = FALSE, startRow = last_year_row + 5,
              startCol = (global_col_count - ncol(ECKWERTE) - 1)
    )
    writeData(wb, ws, ECKWERTE[, -1],
              colNames = TRUE, startRow = last_year_row + 5,
              startCol = (global_col_count - ncol(ECKWERTE) + 1)
    )
    
    addStyle(wb, ws, style_bold, last_year_row + 5, (global_col_count - ncol(ECKWERTE) + 1):global_col_count - 1, stack = TRUE)
    addStyle(wb, ws, style_right_align, last_year_row + 5, (global_col_count - ncol(ECKWERTE) + 1):(global_col_count - 1), stack = TRUE)
    addStyle(wb, ws, style_body_pct1, (last_year_row + 6), (global_col_count - ncol(ECKWERTE) + 1):(global_col_count - 1), stack = TRUE)
    addStyle(wb, ws, style_body_pct1, (last_year_row + 7), (global_col_count - ncol(ECKWERTE) + 1):(global_col_count - 1), stack = TRUE)
    addStyle(wb, ws, style_body_pct1, (last_year_row + 8), (global_col_count - ncol(ECKWERTE) + 1):(global_col_count - 1), stack = TRUE)
    setColWidths(wb, ws, cols = 18:24, widths = 11)
    setColWidths(wb, ws, cols = 21, widths = 11.5)
    
    # --- add the foruml symbole -------------------------------------------------
    # writeData(wb,ws,formul.RR,startCol = 14,startRow = 9)
    # writeData(wb,ws,formul.RC,startCol = 15,startRow = 9)
    # writeData(wb,ws,formul.RE,startCol = 16,startRow = 9)
    # writeData(wb,ws,formul.C,startCol = 17,startRow = 9)
    # addStyle(wb, ws, nb_foot, cols = 14, rows = 9, stack = TRUE)
    # addStyle(wb, ws, nb_foot, cols = 15, rows = 9, stack = TRUE)
    # addStyle(wb, ws, nb_foot, cols = 16, rows = 9, stack = TRUE)
    # addStyle(wb, ws, nb_foot, cols = 17, rows = 9, stack = TRUE)
    # 
    
    
    # --- Percent style for indices ----------------------------------------------
    addStyle(wb, ws, style_body_pct0,
             rows = ((10:last_year_row)) + value_st,
             cols = c(
                 grep("indx_kap_ausg", colnames(DATA)),
                 grep("indx_kap_oiv_ausg", colnames(DATA))
             ),
             stack = TRUE, gridExpand = TRUE
    )
    
    addStyle(wb, ws, style_body_pct1,
             rows = ((10:last_year_row)) + value_st,
             cols = c(
                 grep("indx_ausg_ls", colnames(DATA)),
                 grep("indx_uml_mwst", colnames(DATA)),
                 grep("indx_uml_ls", colnames(DATA)),
                 grep("indx_ersq", colnames(DATA))
             ),
             stack = TRUE, gridExpand = TRUE
    )
    
    # --- Percent style for wr in 3rd col ----------------------------------------
    addStyle(wb, ws, percent_style,
             rows = ((10:last_year_row)) + value_st,
             cols = 3, stack = TRUE, gridExpand = TRUE
    )

}
