#include "htio2/FormatUtil.h"

#include "htio2/Error.h"
#include "htio2/PlainFileHandle.h"
#include "htio2/GzipFileHandle.h"

using namespace std;

namespace htio2
{

CompressFormat guess_compress_by_name(const std::string& file)
{
    if (file.rfind(".gz") != std::string::npos) return COMPRESS_GZIP;
    else return COMPRESS_PLAIN;
}

SeqFormat guess_format_by_name_and_content(const std::string& file, CompressFormat comp)
{
    SeqFormat re = guess_format_by_name(file);
    if (re == FORMAT_UNKNOWN)
    {
        FileHandle* handle = 0;
        if (comp == COMPRESS_GZIP)
            handle = new GzipFileHandle(file.c_str(), READ);
        else if (comp == COMPRESS_PLAIN)
            handle = new PlainFileHandle(file.c_str(), READ);
        else
            throw InvalidCompressFormat(comp);

        re = guess_format_by_content(*handle);
        delete handle;
    }
    return re;
}

SeqFormat guess_format_by_name(const std::string& file)
{
    if (file.rfind(".fastq") != string::npos ||
        file.rfind(".fq") != string::npos)
    {
        return FORMAT_FASTQ;
    }
    else if (file.rfind(".fasta") != string::npos ||
             file.rfind(".fas") != string::npos ||
             file.rfind(".fa") != string::npos ||
             file.rfind(".faa") != string::npos ||
             file.rfind(".fna") != string::npos)
    {
        return FORMAT_FASTA;
    }
    else
    {
        return FORMAT_UNKNOWN;
    }
}

SeqFormat guess_format_by_content(FileHandle& handle)
{
    // read first line, guess format
    string line;
    handle.read_line(line);

    SeqFormat format;
    if (line[0] == '>')
        format = FORMAT_FASTA;
    else if (line[0] == '@')
        format = FORMAT_FASTQ;
    else
        format = FORMAT_UNKNOWN;

    return format;
}

} // namespace htio2
