# Path: mirtop/mirna/fasta.py
# def read_precursor(precursor, sps=None):
# 
# Path: mirtop/mirna/mapper.py
# def guess_database(args):
# def _guess_database_file(gff, database=None):
# def get_primary_transcript(database):
# def read_gtf_to_mirna(gtf):
# def read_gtf_chr2mirna(gtf):  # read from read_gtf_to_precursor
# def read_gtf_chr2mirna2(gtf):  # to remove
# def read_gtf_to_precursor(gtf):
# def _parse_db_mir_chrom(db_mir, db, id_dict):
# def _parse_db_mir(db_mir, db, id_dict):
# def _parse_db_mir_genomic(db_mir, db, id_dict):
# def read_gtf_to_precursor_mirgenedb(gtf, format="precursor"):
# def read_gtf_to_precursor_mirbase(gtf, format="precursor"):
# def liftover_genomic_precursor(read, genome, hairpin, expected=None):
# 
# Path: mirtop/bam/bam.py
# def low_memory_bam(bam_fn, sample, out_handle, args):
#     if args.genomic:
#         raise ValueError("low-memory option is not compatible with genomic coordinates.")
#     precursors = args.precursors
#     bam_fn = _sam_to_bam(bam_fn)
#     bam_fn = _bam_sort(bam_fn)
#     mode = "r" if bam_fn.endswith("sam") else "rb"
#     handle = pysam.Samfile(bam_fn, mode)
#     lines = []
#     current = None
#     for line in handle:
#         if not current or current == line.query_name:
#             lines.append(line)
#             current = line.query_name
#         else:
#             reads = _read_lines(lines, precursors, handle, args)
#             ann = annotate(reads, args.matures, args.precursors, quiet=True)
#             gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#             body.write_body_on_handle(gff_lines, out_handle)
#             current = line.query_name
#             lines = []
#             lines.append(line)
#     reads = _read_lines(lines, precursors, handle, args)
#     ann = annotate(reads, args.matures, args.precursors, quiet=True)
#     gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#     body.write_body_on_handle(gff_lines, out_handle)
# 
# def low_memory_genomic_bam(bam_fn, sample, out_handle, args):
#     logger.info("Reading BAM file in low memory mode.")
#     logger.warning("This is under development and variants can be unexact.")
#     precursors = args.precursors
#     bam_fn = _sam_to_bam(bam_fn)
#     bam_fn = _bam_sort(bam_fn)
#     database = guess_database(args)
#     bed_fn = os.path.join(args.out, os.path.basename(bam_fn) + ".bed")
#     logger.info("Making bed file.")
#     _bed(bam_fn, bed_fn)
#     logger.info("Intersecting bed file.")
#     intersect_fn = intersect(bed_fn, args.gtf)
#     logger.info("Loading database.")
#     # TODO this'll return conn_reads and conn_counts
#     conn = _read_lifted_bam_alpha(intersect_fn, bam_fn, args)
#     rows = sql.select_all_reads(conn)
#     lines = []
#     current = None
#     logger.info("Analyzing database.")
#     for row in rows:
#         if not current or current == row[0]:
#             lines.append(row)
#             current = row[0]
#         else:
#             # TODO counts of sequence = conn_counts.query UID
#             # it could be counts only same location UID+chrom+start, or counts all UID
#             reads = _read_lifted_lines(lines, precursors, database)
#             ann = annotate(reads, args.matures, args.precursors, quiet=True)
#             gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#             body.write_body_on_handle(gff_lines, out_handle)
#             current = row[0]
#             lines = []
#             lines.append(row)
#     reads = _read_lifted_lines(lines, precursors, database)
#     ann = annotate(reads, args.matures, args.precursors, quiet=True)
#     gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#     body.write_body_on_handle(gff_lines, out_handle)
#     conn.close()
#     logger.info("Done")
# 
# Path: mirtop/importer/seqbuster.py
# def header():
# def read_file(fn, args):
# def read_file_low_memory(fn, sample, args, out_handle):
# def _read_line(line, col_fix, precursors):
# def _get_freq(name):
# 
# Path: mirtop/gff/header.py
# def create(samples, database, custom, filter=None):
# def get_gff_version():
# def make_tools(tools):
# def _get_samples(samples):
# def _get_database(database):
# def _filter(filters):
# def read_version(fn):
# def read_samples(fn):


import os.path as op
import mirtop.libs.logger as mylog
from mirtop.mirna import fasta, mapper
from mirtop.bam.bam import low_memory_bam, low_memory_genomic_bam
from mirtop.importer import seqbuster
from mirtop.gff import header
"""mirGFF3 proxy converter"""
from __future__ import print_function


logger = mylog.getLogger(__name__)


def reader(args):
    """
    Realign BAM hits to miRBase to get better accuracy and annotation
    """
    samples = []

# Path: mirtop/mirna/fasta.py
# def read_precursor(precursor, sps=None):
# 
# Path: mirtop/mirna/mapper.py
# def guess_database(args):
# def _guess_database_file(gff, database=None):
# def get_primary_transcript(database):
# def read_gtf_to_mirna(gtf):
# def read_gtf_chr2mirna(gtf):  # read from read_gtf_to_precursor
# def read_gtf_chr2mirna2(gtf):  # to remove
# def read_gtf_to_precursor(gtf):
# def _parse_db_mir_chrom(db_mir, db, id_dict):
# def _parse_db_mir(db_mir, db, id_dict):
# def _parse_db_mir_genomic(db_mir, db, id_dict):
# def read_gtf_to_precursor_mirgenedb(gtf, format="precursor"):
# def read_gtf_to_precursor_mirbase(gtf, format="precursor"):
# def liftover_genomic_precursor(read, genome, hairpin, expected=None):
# 
# Path: mirtop/bam/bam.py
# def low_memory_bam(bam_fn, sample, out_handle, args):
#     if args.genomic:
#         raise ValueError("low-memory option is not compatible with genomic coordinates.")
#     precursors = args.precursors
#     bam_fn = _sam_to_bam(bam_fn)
#     bam_fn = _bam_sort(bam_fn)
#     mode = "r" if bam_fn.endswith("sam") else "rb"
#     handle = pysam.Samfile(bam_fn, mode)
#     lines = []
#     current = None
#     for line in handle:
#         if not current or current == line.query_name:
#             lines.append(line)
#             current = line.query_name
#         else:
#             reads = _read_lines(lines, precursors, handle, args)
#             ann = annotate(reads, args.matures, args.precursors, quiet=True)
#             gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#             body.write_body_on_handle(gff_lines, out_handle)
#             current = line.query_name
#             lines = []
#             lines.append(line)
#     reads = _read_lines(lines, precursors, handle, args)
#     ann = annotate(reads, args.matures, args.precursors, quiet=True)
#     gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#     body.write_body_on_handle(gff_lines, out_handle)
# 
# def low_memory_genomic_bam(bam_fn, sample, out_handle, args):
#     logger.info("Reading BAM file in low memory mode.")
#     logger.warning("This is under development and variants can be unexact.")
#     precursors = args.precursors
#     bam_fn = _sam_to_bam(bam_fn)
#     bam_fn = _bam_sort(bam_fn)
#     database = guess_database(args)
#     bed_fn = os.path.join(args.out, os.path.basename(bam_fn) + ".bed")
#     logger.info("Making bed file.")
#     _bed(bam_fn, bed_fn)
#     logger.info("Intersecting bed file.")
#     intersect_fn = intersect(bed_fn, args.gtf)
#     logger.info("Loading database.")
#     # TODO this'll return conn_reads and conn_counts
#     conn = _read_lifted_bam_alpha(intersect_fn, bam_fn, args)
#     rows = sql.select_all_reads(conn)
#     lines = []
#     current = None
#     logger.info("Analyzing database.")
#     for row in rows:
#         if not current or current == row[0]:
#             lines.append(row)
#             current = row[0]
#         else:
#             # TODO counts of sequence = conn_counts.query UID
#             # it could be counts only same location UID+chrom+start, or counts all UID
#             reads = _read_lifted_lines(lines, precursors, database)
#             ann = annotate(reads, args.matures, args.precursors, quiet=True)
#             gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#             body.write_body_on_handle(gff_lines, out_handle)
#             current = row[0]
#             lines = []
#             lines.append(row)
#     reads = _read_lifted_lines(lines, precursors, database)
#     ann = annotate(reads, args.matures, args.precursors, quiet=True)
#     gff_lines = body.create(ann, args.database, sample, args, quiet=True)
#     body.write_body_on_handle(gff_lines, out_handle)
#     conn.close()
#     logger.info("Done")
# 
# Path: mirtop/importer/seqbuster.py
# def header():
# def read_file(fn, args):
# def read_file_low_memory(fn, sample, args, out_handle):
# def _read_line(line, col_fix, precursors):
# def _get_freq(name):
# 
# Path: mirtop/gff/header.py
# def create(samples, database, custom, filter=None):
# def get_gff_version():
# def make_tools(tools):
# def _get_samples(samples):
# def _get_database(database):
# def _filter(filters):
# def read_version(fn):
# def read_samples(fn):


# Path: mirtop/gff/read.py
import os.path as op
import mirtop.libs.logger as mylog
from mirtop.mirna import fasta, mapper
from mirtop.bam.bam import low_memory_bam, low_memory_genomic_bam
from mirtop.importer import seqbuster
from mirtop.gff import header

"""mirGFF3 proxy converter"""
from __future__ import print_function


logger = mylog.getLogger(__name__)


def reader(args):
    """
    Realign BAM hits to miRBase to get better accuracy and annotation
    """
    samples = []

    database = mapper.guess_database(args)