#!/usr/bin/python -3
#
# Copyright (c) 2012 Mikkel Schubert <MSchubert@snm.ku.dk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from __future__ import print_function

import sys
import time

from pypeline.common.utilities import fragment, cumsum


_DESC  = "Processed {Reads} reads ({Progress}) in {Time}, est. {Remaining} left. Last {ReadsDelta} reads in {TimeDelta}, now at {Contig}: {Position} ..."
_FINAL = "Processed {Reads} reads in {Time}. Last {ReadsDelta} reads in {TimeDelta} ..."

class BAMTimer:
    def __init__(self, bamfile, desc = None, step = 1e6, out = sys.stderr):
        self._bam   = bamfile
        self._out   = out
        self._desc  = desc
        self._step  = step
        self._count = 0
        self._last_count = 0
        self._last_time  = time.time()
        self._start_time = self._last_time

        self._total  = 0.0
        self._counts = []
        if bamfile:
            self._total  = float(sum(bamfile.lengths)) or 1.0
            self._counts = list(cumsum(bamfile.lengths))


    def increment(self, count = 1, read = None):
        self._count += count
        if (self._count - self._last_count) >= self._step:
            desc = _DESC if self._bam else _FINAL
            current_time = time.time()
            self._print(desc, current_time, read)
            self._last_time  = current_time
            self._last_count = self._count
        return self


    def finalize(self):
        self._print(_FINAL, time.time(), None)


    def _print(self, desc, current_time, read):
        contig, position, progress, remaining = "NA", "NA", "NA", "NA"
        if read and self._bam:
            contig   = self._bam.references[read.tid]
            position = self._format_int(read.pos + 1)
            fraction = ((read.pos + self._counts[read.tid]) / self._total)
            progress = "%.2f%%" % fraction

            current_running = current_time - self._start_time
            remaining = self._format_time(current_running / fraction - current_running)

        if self._desc:
            print("%s: " % self._desc, end = "", file = self._out)

        print(desc.format(Reads      = self._format_int(self._count),
                          ReadsDelta = self._format_int(self._count - self._last_count),
                          Time       = self._format_time(current_time - self._start_time),
                          TimeDelta  = self._format_time(current_time - self._last_time),
                          Contig     = contig,
                          Position   = position,
                          Progress   = progress,
                          Remaining  = remaining),
            file = self._out)


    def _format_time(self, ftime):
        utc = time.gmtime(ftime)
        return "%02i:%02i:%02is" % (utc.tm_hour, utc.tm_min, utc.tm_sec)

    def _format_int(self, value):
        return (",".join(fragment(3, str(value)[::-1])))[::-1]

@@ -1612,22 +1612,19 @@
 bam   = 
-bamfil
+Non
 e%0A      
@@ -1831,16 +1831,48 @@
 ast_time
+%0A        self._last_fract = -1.0
 %0A%0A      
@@ -1936,17 +1936,116 @@
  bamfile
-:
+ and bamfile.header.get(%22HD%22, %7B%7D).get(%22SO%22, %22NA%22) == %22coordinate%22:%0A            self._bam   = bamfile
 %0A       
@@ -2061,17 +2061,16 @@
 ._total 
- 
 = float(
@@ -2126,15 +2126,50 @@
 unts
- = list
+.append(0)%0A            self._counts.extend
 (cum
@@ -2333,58 +2333,8 @@
 ep:%0A
-            desc = _DESC if self._bam else _FINAL%0A
     
@@ -2392,22 +2392,16 @@
 ._print(
-desc, 
 current_
@@ -2569,16 +2569,8 @@
 int(
-_FINAL, 
 time
@@ -2610,14 +2610,8 @@
 elf,
- desc,
  cur
@@ -2628,16 +2628,38 @@
  read):%0A
+        desc = _FINAL%0A
         
@@ -2745,72 +2745,118 @@
 and 
-self._bam:%0A            contig   = self._bam.references%5Bread.tid%5D
+not read.is_unmapped and self._bam:%0A            fraction = ((read.pos + self._counts%5Bread.tid%5D) / self._total)
 %0A   
@@ -2868,25 +2868,29 @@
     
-posi
+if frac
 tion 
+%3E
 = self._
 form
@@ -2889,108 +2889,184 @@
 lf._
-format_int(read.pos + 1)%0A            fraction = ((read.pos + self._counts%5Bread.tid%5D) / self._total)%0A
+last_fract:%0A                self._last_fract = fraction%0A                contig   = self._bam.references%5Bread.tid%5D%0A                position = self._format_int(read.pos + 1)%0A    
     
@@ -3095,24 +3095,25 @@
 2f%25%25%22 %25 
+(
 fraction
 %0A%0A      
@@ -3104,18 +3104,30 @@
 fraction
-%0A%0A
+ * 100,)%0A%0A    
         
@@ -3192,16 +3192,20 @@
         
+ 
+   
 remainin
@@ -3271,16 +3271,202 @@
 running)
+%0A                desc      = _DESC%0A            else:%0A                print(%22File appears to be unsorted, cannot estimate progress ...%22, file = self._out)%0A                self._bam = None
 %0A%0A      

Improve timer handling of unsorted/unmapped reads.