#' Generates links to index pages listing individual articles..
#'
#' Generates links to index pages listing individual articles.
#'
#' @param linkFirstChunk First part of index link that does not change in other index pages.
#' @param linkSecondChunk Part of index link appneded after the part of the link that varies. If not relevant, may be left empty.
#' @param startPage If the links include a numerical component, define first number of the sequence. startPage defaults to 1.
#' @param endPage If the links include a numerical component, define first number of the sequence. endPage defaults to 10.
#' @param increaseBy Defines by how much the number in the link should be increased in the numerical sequence. Defaults to 1.
#' @param dateFormat A charachter string that defines the format of the date to incldue in the link. Available options are: "Y" (e.g. 2015), "Ym" (2015-10), "Ymd" (e.g. 2015-10-24).
#' @param more Defaults to NULL. If given, it can be used to create links based on multiple parameters. FIXME It must be a data frame, create a template with `CreateLinks_template <- tibble::as_tibble(data.frame(matrix(nrow=0,ncol=length(c("linkFirstChunk","linkSecondChunk","startPage", "endPage", "increaseBy","dateFormat","startDate", "endDate",   "dateSeparator", "reversedOrder")))))`; `names(CreateLinks_template) <- params_available` ; `readr::write_csv(x = CreateLinks_template, path = "CreateLinks_template.csv")`
#' @param export Exports the links generated by the function in a .txt file in the folder project/website.
#' @param importParameters Defaults to NULL. If TRUE, ignores all parameters given in the function call, and imports them from parameters file stored in "project/website/Logs/parameters.rds".
#' @param exportParameters Defaults to TRUE. If TRUE, function parameters are exported in the project/website folder. They can be used to update the corpus. Requires parameters project/website.
#' @param project Name of 'castarter' project. Must correspond to the name of a folder in the current working directory. Not required if previously set with SetCastarter(project = "project", website = "website")
#' @param website Name of a website included in a 'castarter' project. Must correspond to the name of a sub-folder of the project folder. Not required if previously set with SetCastarter(project = "project", website = "website")
#' @return A character vector of links to index pages.
#' @export
#' @examples
#' \dontrun{
#' indexLinks <- CreateLinks("http://www.example.com/news/")
#' }
CreateLinks <- function(linkFirstChunk,
                        linkSecondChunk = NULL,
                        startPage = 1,
                        endPage = 10,
                        increaseBy = 1,
                        dateFormat = NULL,
                        startDate = NULL,
                        endDate = NULL,
                        dateSeparator = "-",
                        reversedOrder = FALSE,
                        more = NULL,
                        export = FALSE,
                        importParameters = NULL,
                        exportParameters = TRUE,
                        project = NULL,
                        website = NULL) {
    # If `project` and `website` not given, tries to get them from environment
    if (is.null(project) == TRUE) {
        project <- CastarterOptions("project")
    }
    if (is.null(website) == TRUE) {
        website <- CastarterOptions("website")
    }
    if (is.null(CastarterOptions("baseFolder"))) {
        baseFolder <- "castarter"
    } else {
        baseFolder <- CastarterOptions("baseFolder")
    }
    if (is.null(importParameters)==FALSE) {
        if (importParameters == TRUE) { # Import parameters
            if (file.exists(base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-"))) == TRUE) {
                params <- readRDS(base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-")))
                params$CreateLinks$exportParameters <- FALSE
                for (i in seq_along(params$CreateLinks)) {
                    assign(names(params$CreateLinks)[i], params$CreateLinks[[i]])
                }
            } else {
                # throw error if parameters file not found
                stop(paste("Parameters file not found in", base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-"))))
            }
            if (exportParameters==TRUE) {
                stop("Parameters can either be imported or exported ('exportParameters' and 'importParameters' cannot both be TRUE.")
            }
        }
    } else {
        importParameters <- FALSE
    }
    if (exportParameters == TRUE & importParameters == FALSE) { # Export parameters
        createLinksParams <- as.list(environment())
        if (file.exists(base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-"))) == TRUE) {
            params <- readRDS(base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-")))
            params$CreateLinks <- NULL
        } else {
            params <- list()
        }
        params$CreateLinks <- createLinksParams
        saveRDS(object = params, file = base::file.path(baseFolder, project, website, "Logs", paste(project, website, "parameters.rds", sep = "-")))
    }

    if (is.null(more)) {
        ## FIXME Same block of code as below, move to separate, non-exported function
        # Create links based on date format, if provided
        if (is.null(dateFormat) == FALSE) {
            if (dateFormat == "ymd" | dateFormat == "Ymd" ) {
                dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                dates <- base::format(as.Date(dates), paste("%Y", "%m", "%d", sep = dateSeparator))
            } else if (dateFormat == "YBd") {
                dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                dates <- base::format(as.Date(dates), paste("%Y", "%B", "%d", sep = dateSeparator))
            }   else if (dateFormat == "ym" | dateFormat == "Ym") {
                dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "month")
                dates <- base::format(as.Date(dates), paste("%Y", "%m", sep = dateSeparator))
            } else if (dateFormat == "Y"|dateFormat == "y"|dateFormat == "year") {
                dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "year")
                dates <- base::format(as.Date(dates), paste("%Y", sep = dateSeparator))
            }  else if (dateFormat == "dmY") {
                dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                dates <- base::format(as.Date(dates), paste("%d", "%m", "%Y", sep = dateSeparator))
            }
            links <- paste0(linkFirstChunk, dates)
        } else { # if not based on date, then create links based on numbers
            links <- base::paste0(linkFirstChunk,
                                  trimws(x = format(base::seq(startPage, endPage, increaseBy), scientific = FALSE), which = "left"))
        }
        # if linkSecondChunk present, append
        if (is.null(linkSecondChunk) == FALSE) {
            links <- base::paste0(links, linkSecondChunk)
        }

    } else {
        links_list <- list()

        for (i in 1:nrow(more)) {

            params_list <- more %>%
                dplyr::slice(i) %>%
                as.list()

            for (j in seq_along(params_list)) {
                if (is.na(params_list[[j]])) {
                    assign(names(params_list)[j], NULL)
                } else {
                    assign(names(params_list)[j], params_list[[j]])
                }
            }

            if (is.null(dateFormat) == FALSE) {
                if (dateFormat == "ymd" | dateFormat == "Ymd" ) {
                    dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                    dates <- base::format(as.Date(dates), paste("%Y", "%m", "%d", sep = dateSeparator))
                } else if (dateFormat == "YBd") {
                    dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                    dates <- base::format(as.Date(dates), paste("%Y", "%B", "%d", sep = dateSeparator))
                }   else if (dateFormat == "ym" | dateFormat == "Ym") {
                    dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "month")
                    dates <- base::format(as.Date(dates), paste("%Y", "%m", sep = dateSeparator))
                } else if (dateFormat == "Y"|dateFormat == "y"|dateFormat == "year") {
                    dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "year")
                    dates <- base::format(as.Date(dates), paste("%Y", sep = dateSeparator))
                }  else if (dateFormat == "dmY") {
                    dates <- base::seq(as.Date(startDate), as.Date(endDate), by = "day")
                    dates <- base::format(as.Date(dates), paste("%d", "%m", "%Y", sep = dateSeparator))
                }
                links <- paste0(linkFirstChunk, dates)
            } else { # if not based on date, then create links based on numbers
                links <- base::paste0(linkFirstChunk,
                                      trimws(x = format(base::seq(startPage, endPage, increaseBy), scientific = FALSE), which = "left"))
            }
            # if linkSecondChunk present, append
            if (is.null(linkSecondChunk) == FALSE) {
                links <- base::paste0(links, linkSecondChunk)
            }

            links_list[[i]] <- links
        }
        links <- unlist(links_list)
    }

    if (reversedOrder == TRUE) {
        links <- base::rev(links)
    }



    if (export == TRUE) {
        base::writeLines(links, base::file.path(baseFolder, project, website, "Logs", paste(Sys.Date(), website, "Logs", "indexLinks.txt", sep = " - ")))
    }
    links
}
