#include "TestConfig.h"
#include "TestFramework.h"

#include "htio2/PairedEndIO.h"
#include "htio2/PlainFileHandle.h"
#include "htio2/Cast.h"

#include <set>

using namespace std;

void read_idx(const string& file, vector<int64_t>& result)
{
    htio2::PlainFileHandle fh(file, htio2::READ);
    string line;
    while (fh.read_line(line))
    {
        int64_t idx;
        if (!htio2::from_string<int64_t>(line, idx))
        {
            fprintf(stderr, "failed to parse line to integer: \"%s\"\n", line.c_str());
            abort();
        }
        printf("  %ld\n", idx);
        result.push_back(idx);
    }
}

bool operator == (htio2::FastqSeq& seq1, htio2::FastqSeq& seq2)
{
    return seq1.id == seq2.id && seq1.desc == seq2.desc && seq1.seq == seq2.seq && seq1.quality == seq2.quality;
}

void TestFramework::content()
{
    const char* cmd = "../src/ht2-sample -P"
                      " -i " TEST_SOURCE_DIR "/test1.fastq.gz " TEST_SOURCE_DIR "/test2.fastq.gz"
                      " -o sample"
                      " --out-id sample_id"
                      " --seed 3 --num 15";
    ok(!system(cmd), cmd);

    vector<int64_t> idx_used;
    read_idx("sample_id", idx_used);
    IS(idx_used.size(), 15);

    htio2::PairedEndIO fh_input(TEST_SOURCE_DIR "/test1.fastq.gz",
                                TEST_SOURCE_DIR "/test2.fastq.gz",
                                htio2::READ,
                                htio2::STRAND_FWD,
                                htio2::STRAND_REV);

    htio2::FastqSeq seq1;
    htio2::FastqSeq seq2;
    vector<htio2::FastqSeq> seqs_1;
    vector<htio2::FastqSeq> seqs_2;

    while (fh_input.next_pair(seq1, seq2, htio2::STRAND_FWD, htio2::STRAND_REV))
    {
        seqs_1.push_back(seq1);
        seqs_2.push_back(seq2);
    }

    htio2::PairedEndIO fh_result("sample_1.fastq.gz",
                                 "sample_2.fastq.gz",
                                 htio2::READ,
                                 htio2::STRAND_FWD,
                                 htio2::STRAND_REV);


    size_t n = 0;
    while (fh_result.next_pair(seq1, seq2, htio2::STRAND_FWD, htio2::STRAND_REV))
    {
        IS(seq1.desc[0], '1');
        IS(seq2.desc[0], '2');
        OK(seqs_1[idx_used[n]] == seq1);
        OK(seqs_2[idx_used[n]] == seq2);
        n++;
    }

}
