# Path: chanjo_report/server/extensions.py

# 
# Path: chanjo_report/server/constants.py
# LEVELS = OrderedDict([
#     (10, 'completeness_10'),
#     (15, 'completeness_15'),
#     (20, 'completeness_20'),
#     (50, 'completeness_50'),
#     (100, 'completeness_100'),
# ])
# 
# Path: chanjo_report/server/blueprints/report/utils.py
# def samplesex_rows(sample_ids):
#     """Generate sex prediction info rows."""
#     sex_query = (api.query(
#         TranscriptStat.sample_id,
#         Transcript.chromosome,
#         func.avg(TranscriptStat.mean_coverage)
#     ).join(
#         TranscriptStat.transcript
#     ).filter(
#         Transcript.chromosome.in_(['X', 'Y']),
#         TranscriptStat.sample_id.in_(sample_ids)
#     ).group_by(
#         TranscriptStat.sample_id,
#         Transcript.chromosome
#     ))
# 
#     samples = itertools.groupby(sex_query, lambda row: row[0])
#     for sample_id, chromosomes in samples:
#         chr_coverage = [coverage for _, _, coverage in chromosomes]
#         LOG.debug('predicting sex')
#         predicted_sex = predict_sex(*chr_coverage)
#         sample_obj = Sample.query.get(sample_id)
#         sample_row = {
#             'sample': sample_obj.name or sample_obj.id,
#             'group': sample_obj.group_name,
#             'analysis_date': sample_obj.created_at,
#             'sex': predicted_sex,
#             'x_coverage': chr_coverage[0],
#             'y_coverage': chr_coverage[1],
#         }
#         yield sample_row
# 
# def keymetrics_rows(samples_ids, genes=None):
#     """Generate key metrics rows."""
#     query = (
#         api.query(
#             TranscriptStat,
#             func.avg(TranscriptStat.mean_coverage).label('mean_coverage'),
#             func.avg(TranscriptStat.completeness_10).label('completeness_10'),
#             func.avg(TranscriptStat.completeness_15).label('completeness_15'),
#             func.avg(TranscriptStat.completeness_20).label('completeness_20'),
#             func.avg(TranscriptStat.completeness_50).label('completeness_50'),
#             func.avg(TranscriptStat.completeness_100).label('completeness_100'),
#         )
#         .filter(TranscriptStat.sample_id.in_(samples_ids))
#         .group_by(TranscriptStat.sample_id)
#     )
# 
#     if genes:
#         query = (query.join(TranscriptStat.transcript)
#                       .filter(Transcript.gene_id.in_(genes)))
#     return query
# 
# def transcripts_rows(sample_ids, genes=None, level=10):
#     """Generate metrics rows for transcripts."""
#     for sample_id in sample_ids:
#         sample_obj = Sample.query.get(sample_id)
#         all_tx = TranscriptStat.query.filter_by(sample_id=sample_id)
#         if genes:
#             all_tx = (all_tx.join(TranscriptStat.transcript)
#                             .filter(Transcript.gene_id.in_(genes)))
#         tx_count = all_tx.count()
#         stat_field = getattr(TranscriptStat, LEVELS[level])
#         missed_tx = all_tx.filter(stat_field < 100)
#         missed_count = missed_tx.count()
#         if tx_count == 0:
#             tx_yield = 0
#             flash("no matching transcripts found!")
#         else:
#             tx_yield = 100 - (missed_count / tx_count * 100)
#         yield {
#             'sample': sample_obj,
#             'yield': tx_yield,
#             'missed': missed_tx,
#             'missed_count': missed_count,
#             'total': tx_count,
#         }
# 
# def map_samples(group_id=None, sample_ids=None):
#     if group_id:
#         query = Sample.query.filter(Sample.group_id == group_id)
#     elif sample_ids:
#         query = Sample.query.filter(Sample.id.in_(sample_ids))
#     else:
#         query = Sample.query
#     try:
#         samples = {sample_obj.id: sample_obj for sample_obj in query}
#         return samples
#     except OperationalError as error:
#         LOG.exception(error)
#         api.session.rollback()
#         return abort(500, 'MySQL error, try again')
# 
# def transcript_coverage(api, gene_id, *sample_ids):
#     """Return coverage metrics per transcript for a given gene."""
#     query = (api.query(TranscriptStat)
#                 .join(TranscriptStat.transcript)
#                 .filter(Transcript.gene_id == gene_id)
#                 .order_by(TranscriptStat.transcript_id,
#                           TranscriptStat.sample_id))
#     if sample_ids:
#         query = query.filter(TranscriptStat.sample_id.in_(sample_ids))
# 
#     tx_groups = itertools.groupby(query, key=lambda tx: tx.transcript_id)
#     return tx_groups


import logging
from chanjo.store.models import Transcript, TranscriptStat, Sample
from flask import abort, Blueprint, render_template, request, url_for
from flask_weasyprint import render_pdf
from chanjo_report.server.extensions import api
from chanjo_report.server.constants import LEVELS
from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples,
                    transcript_coverage)
# -*- coding: utf-8 -*-



logger = logging.getLogger(__name__)
report_bp = Blueprint('report', __name__, template_folder='templates',
                      static_folder='static', static_url_path='/static/report')


@report_bp.route('/genes/<gene_id>')
def gene(gene_id):
    """Display coverage information on a gene."""
    sample_ids = request.args.getlist('sample_id')
    sample_dict = map_samples(sample_ids=sample_ids)
    matching_tx = Transcript.filter_by(gene_id=gene_id).first()
    if matching_tx is None:
        return abort(404, "gene not found: {}".format(gene_id))
    gene_name = matching_tx.gene_name

# Path: chanjo_report/server/extensions.py

# 
# Path: chanjo_report/server/constants.py
# LEVELS = OrderedDict([
#     (10, 'completeness_10'),
#     (15, 'completeness_15'),
#     (20, 'completeness_20'),
#     (50, 'completeness_50'),
#     (100, 'completeness_100'),
# ])
# 
# Path: chanjo_report/server/blueprints/report/utils.py
# def samplesex_rows(sample_ids):
#     """Generate sex prediction info rows."""
#     sex_query = (api.query(
#         TranscriptStat.sample_id,
#         Transcript.chromosome,
#         func.avg(TranscriptStat.mean_coverage)
#     ).join(
#         TranscriptStat.transcript
#     ).filter(
#         Transcript.chromosome.in_(['X', 'Y']),
#         TranscriptStat.sample_id.in_(sample_ids)
#     ).group_by(
#         TranscriptStat.sample_id,
#         Transcript.chromosome
#     ))
# 
#     samples = itertools.groupby(sex_query, lambda row: row[0])
#     for sample_id, chromosomes in samples:
#         chr_coverage = [coverage for _, _, coverage in chromosomes]
#         LOG.debug('predicting sex')
#         predicted_sex = predict_sex(*chr_coverage)
#         sample_obj = Sample.query.get(sample_id)
#         sample_row = {
#             'sample': sample_obj.name or sample_obj.id,
#             'group': sample_obj.group_name,
#             'analysis_date': sample_obj.created_at,
#             'sex': predicted_sex,
#             'x_coverage': chr_coverage[0],
#             'y_coverage': chr_coverage[1],
#         }
#         yield sample_row
# 
# def keymetrics_rows(samples_ids, genes=None):
#     """Generate key metrics rows."""
#     query = (
#         api.query(
#             TranscriptStat,
#             func.avg(TranscriptStat.mean_coverage).label('mean_coverage'),
#             func.avg(TranscriptStat.completeness_10).label('completeness_10'),
#             func.avg(TranscriptStat.completeness_15).label('completeness_15'),
#             func.avg(TranscriptStat.completeness_20).label('completeness_20'),
#             func.avg(TranscriptStat.completeness_50).label('completeness_50'),
#             func.avg(TranscriptStat.completeness_100).label('completeness_100'),
#         )
#         .filter(TranscriptStat.sample_id.in_(samples_ids))
#         .group_by(TranscriptStat.sample_id)
#     )
# 
#     if genes:
#         query = (query.join(TranscriptStat.transcript)
#                       .filter(Transcript.gene_id.in_(genes)))
#     return query
# 
# def transcripts_rows(sample_ids, genes=None, level=10):
#     """Generate metrics rows for transcripts."""
#     for sample_id in sample_ids:
#         sample_obj = Sample.query.get(sample_id)
#         all_tx = TranscriptStat.query.filter_by(sample_id=sample_id)
#         if genes:
#             all_tx = (all_tx.join(TranscriptStat.transcript)
#                             .filter(Transcript.gene_id.in_(genes)))
#         tx_count = all_tx.count()
#         stat_field = getattr(TranscriptStat, LEVELS[level])
#         missed_tx = all_tx.filter(stat_field < 100)
#         missed_count = missed_tx.count()
#         if tx_count == 0:
#             tx_yield = 0
#             flash("no matching transcripts found!")
#         else:
#             tx_yield = 100 - (missed_count / tx_count * 100)
#         yield {
#             'sample': sample_obj,
#             'yield': tx_yield,
#             'missed': missed_tx,
#             'missed_count': missed_count,
#             'total': tx_count,
#         }
# 
# def map_samples(group_id=None, sample_ids=None):
#     if group_id:
#         query = Sample.query.filter(Sample.group_id == group_id)
#     elif sample_ids:
#         query = Sample.query.filter(Sample.id.in_(sample_ids))
#     else:
#         query = Sample.query
#     try:
#         samples = {sample_obj.id: sample_obj for sample_obj in query}
#         return samples
#     except OperationalError as error:
#         LOG.exception(error)
#         api.session.rollback()
#         return abort(500, 'MySQL error, try again')
# 
# def transcript_coverage(api, gene_id, *sample_ids):
#     """Return coverage metrics per transcript for a given gene."""
#     query = (api.query(TranscriptStat)
#                 .join(TranscriptStat.transcript)
#                 .filter(Transcript.gene_id == gene_id)
#                 .order_by(TranscriptStat.transcript_id,
#                           TranscriptStat.sample_id))
#     if sample_ids:
#         query = query.filter(TranscriptStat.sample_id.in_(sample_ids))
# 
#     tx_groups = itertools.groupby(query, key=lambda tx: tx.transcript_id)
#     return tx_groups


# Path: chanjo_report/server/blueprints/report/views.py
import logging
from chanjo.store.models import Transcript, TranscriptStat, Sample
from flask import abort, Blueprint, render_template, request, url_for
from flask_weasyprint import render_pdf
from chanjo_report.server.extensions import api
from chanjo_report.server.constants import LEVELS
from .utils import (samplesex_rows, keymetrics_rows, transcripts_rows, map_samples,
                    transcript_coverage)

# -*- coding: utf-8 -*-



logger = logging.getLogger(__name__)
report_bp = Blueprint('report', __name__, template_folder='templates',
                      static_folder='static', static_url_path='/static/report')


@report_bp.route('/genes/<gene_id>')
def gene(gene_id):
    """Display coverage information on a gene."""
    sample_ids = request.args.getlist('sample_id')
    sample_dict = map_samples(sample_ids=sample_ids)
    matching_tx = Transcript.filter_by(gene_id=gene_id).first()
    if matching_tx is None:
        return abort(404, "gene not found: {}".format(gene_id))
    gene_name = matching_tx.gene_name

    tx_groups = transcript_coverage(api, gene_id, *sample_ids)