library(seqmagick)

x <- Biostrings::BStringSet(c("s1"="AAAA", "s2"="CCCC", "s3"="GGGG"))
mapping <- data.frame(V1=c("s1", "s2"),
                      V2=c("human", "mouse"))

test_that("bs_rename replaces matching names and keeps unmatched ones", {
    z <- expect_message(bs_rename(x, mapping), "failed to rename")
    expect_identical(names(z), c("human", "mouse", "s3"))
    expect_identical(unname(as.character(z)), unname(as.character(x)))
})

test_that("bs_rename prefix/suffix modes", {
    p <- bs_rename(x[1:2], mapping, mode="prefix")
    expect_identical(names(p), c("humans1", "mouses2"))

    s <- bs_rename(x[1:2], mapping, mode="suffix")
    expect_identical(names(s), c("s1human", "s2mouse"))
})

test_that("bs_rename with sep and position", {
    y <- Biostrings::BStringSet(c("s1 v2"="AAAA", "s2 v2"="CCCC", "s3 v2"="GGGG"))
    m <- data.frame(V1=c("s1", "s2"), V2=c("human", "mouse"))

    ## replace token at position 2
    z <- bs_rename(y, m, sep=" ", position=2)
    expect_identical(names(z), c("s1 human", "s2 mouse", "s3 v2"))

    ## replace token at position 1
    z1 <- bs_rename(y, m, sep=" ", position=1)
    expect_identical(names(z1), c("human v2", "mouse v2", "s3 v2"))
})

test_that("position requires separator", {
    expect_error(bs_rename(x, mapping, position=1),
                 "separator should be provided")
})

test_that("fa_rename end-to-end writes output file", {
    fasfile <- tempfile(fileext=".fas")
    fa_write(x, fasfile)

    mapfile <- tempfile()
    write.table(mapping, mapfile, sep="\t", quote=FALSE,
                row.names=FALSE, col.names=FALSE)

    outfile <- tempfile(fileext=".fas")
    z <- invisible(fa_rename(fasfile, mapfile, outfile=outfile))
    expect_identical(names(z)[1:2], c("human", "mouse"))

    reread <- fa_read(outfile)
    expect_identical(names(reread), c("human", "mouse", "s3"))

    unlink(c(fasfile, mapfile, outfile))
})
