#! /usr/bin/env python
# -*- coding: utf-8 -*-

"""
Simple subtitle shifting script.

Usage : python srt-shift.py [-r] SRT_FILE SHIFT_SECS

-r          Replace the file. If not used, the synchronized subtitles will be 
            written in "SRT_FILE.shifted"

STR_FILE    File to synchronize. Must be srt format.

DELAY_SECS  Amount of time (in seconds) to shift the subtitles. Can be negative

"""
from datetime import timedelta, datetime

FORMAT = '%H:%M:%S'

def shift_line(line, t_delay):
    """
    Shift the start and end dates in a line by adding t_delay
    line: the line to process 
        (must be on the form HH:MM:SS,mmm --> HH:MM:SS,mmm)
    t_delay: datetime.timedelta object describing the amount of time to shift
             the dates with.  

    """
    s_time = line.split(' --> ')
    for idx in 0, 1:
        hms = s_time[i].split(',')
        hms[0] = (datetime.strptime(hms[0],FORMAT) + delay).strftime(FORMAT)
        s_time[i] = ','.join(hms)
    return ' --> '.join(s_time)

def process_file(path, delay, replace=False):
    """
    Processes an srt file. Shifts all subtitles with given delay in seconds.
    path: path of the srt file
    delay: integer delay in seconds
    replace: if True, replace the processed file, else write result to
        "file.shifted"

    """
    t_delay = timedelta(seconds=delay)
    f = open(path, 'rw')
    res = ''
    for line in f:
        if '-->' in line:
            line = shift_line(line, t_delay)
        res += line

    if not replace:
        f.close()
        pathres = path + '.shifted'
        f = open(pathres, 'w')
    f.write(res)
    f.close()

if __name__ == '__main__':
    import sys
    replace = False
    if '-r' in sys.argv:
        replace = True
    path = sys.argv[-2]
    delay = int(sys.argv[-1])
    if path.split('.')[-1] == 'srt':
        process_file(path, delay, replace)
    else:
        print 'usage : python  srt-shift.py  [-r]  srt_file_path  time_delay'
        
