# Path: seqcluster/libs/inputs.py
# def parse_ma_file(seq_obj, in_file):
#     """
#     read seqs.ma file and create dict with
#     sequence object
#     """
#     name = ""
#     index = 1
#     total = defaultdict(int)
#     ratio = list()
#     with open(in_file) as handle_in:
#         line = handle_in.readline().strip()
#         cols = line.split("\t")
#         samples = cols[2:]
#         for line in handle_in:
#             line = line.strip()
#             cols = line.split("\t")
#             name = int(cols[0].replace("seq_", ""))
#             seq = cols[1]
#             exp = {}
#             for i in range(len(samples)):
#                 exp[samples[i]] = int(cols[i+2])
#                 total[samples[i]] += int(cols[i+2])
#             ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
#             index = index+1
#             if name in seq_obj:
#                 seq_obj[name].set_freq(exp)
#                 seq_obj[name].set_seq(seq)
#             # new_s = sequence(seq, exp, index)
#             # seq_l[name] = new_s
#     df = pd.DataFrame(ratio)
#     df = df[(df.T != 0).all()]
#     size_factor = dict(zip(samples, df.median(axis=0)))
#     seq_obj = _normalize_seqs(seq_obj, size_factor)
#     return seq_obj, total, index
# 
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False


import os
import pysam
import logging
import json
from seqcluster.libs.inputs import parse_ma_file
from seqcluster.libs.sam2bed import makeBED
from collections import defaultdict, Counter

logger = logging.getLogger('stats')


def stats(args):
    """Create stats from the analysis
    """
    logger.info("Reading sequences")
    data = parse_ma_file(args.ma)
    logger.info("Get sequences from sam")
    is_align = _read_sam(args.sam)
    is_json, is_db = _read_json(args.json)
    res = _summarise_sam(data, is_align, is_json, is_db)
    _write_suma(res, os.path.join(args.out, "stats_align.dat"))
    logger.info("Done")


def _read_sam(sam):
    is_align = set()
    with pysam.Samfile(sam, "rb") as samfile:
        for a in samfile.fetch():

# Path: seqcluster/libs/inputs.py
# def parse_ma_file(seq_obj, in_file):
#     """
#     read seqs.ma file and create dict with
#     sequence object
#     """
#     name = ""
#     index = 1
#     total = defaultdict(int)
#     ratio = list()
#     with open(in_file) as handle_in:
#         line = handle_in.readline().strip()
#         cols = line.split("\t")
#         samples = cols[2:]
#         for line in handle_in:
#             line = line.strip()
#             cols = line.split("\t")
#             name = int(cols[0].replace("seq_", ""))
#             seq = cols[1]
#             exp = {}
#             for i in range(len(samples)):
#                 exp[samples[i]] = int(cols[i+2])
#                 total[samples[i]] += int(cols[i+2])
#             ratio.append(np.array(list(exp.values())) / np.mean(list(exp.values())))
#             index = index+1
#             if name in seq_obj:
#                 seq_obj[name].set_freq(exp)
#                 seq_obj[name].set_seq(seq)
#             # new_s = sequence(seq, exp, index)
#             # seq_l[name] = new_s
#     df = pd.DataFrame(ratio)
#     df = df[(df.T != 0).all()]
#     size_factor = dict(zip(samples, df.median(axis=0)))
#     seq_obj = _normalize_seqs(seq_obj, size_factor)
#     return seq_obj, total, index
# 
# Path: seqcluster/libs/sam2bed.py
# def makeBED(samFields):
#     samFlag = int(samFields.flag)
#     # Only create a BED entry if the read was aligned
#     if (not (samFlag & 0x0004)) and samFields.pos:
#             name = samFields.qname
#             seq = name.split("-")[1]
#             chrom = samFields.rname
#             start = str(int(samFields.pos))
#             end = str(int(samFields.pos) + len(seq) - 1)
#             strand = getStrand(samFlag)
#             # Write out the BED entry
#             return bedaligned("%s\t%s\t%s\t%s\t.\t%s\n" %  (chrom, start, end, name, strand))
#     else:
#             return False


# Path: seqcluster/stats.py
import os
import pysam
import logging
import json
from seqcluster.libs.inputs import parse_ma_file
from seqcluster.libs.sam2bed import makeBED
from collections import defaultdict, Counter


logger = logging.getLogger('stats')


def stats(args):
    """Create stats from the analysis
    """
    logger.info("Reading sequences")
    data = parse_ma_file(args.ma)
    logger.info("Get sequences from sam")
    is_align = _read_sam(args.sam)
    is_json, is_db = _read_json(args.json)
    res = _summarise_sam(data, is_align, is_json, is_db)
    _write_suma(res, os.path.join(args.out, "stats_align.dat"))
    logger.info("Done")


def _read_sam(sam):
    is_align = set()
    with pysam.Samfile(sam, "rb") as samfile:
        for a in samfile.fetch():

            a = makeBED(a)