import re
import difflib
import math

def sentence_time_ratio(text,maxLen):
    
    total_len = len(text)
    if total_len > maxLen:
        left_word = total_len % maxLen
        times = int(math.ceil(total_len/maxLen))
        if left_word < 5:
            times+=1
        sen_len = int(total_len/times)
    
        time_ratio = [None]*times
        sentences = [None]*times
        print(times,',',total_len,",",sen_len)
        for t in range(times):
            
            sentences[t] = text[t*sen_len:t*sen_len+sen_len]
            time_ratio[t] = len(sentences[t])/total_len
    else:
        time_ratio = [1]
        sentences = [text]
    
    return time_ratio, sentences
#1 sentence in, spliited array out


def parse_script(file_path,gt_list):
    with open(file_path, 'r',encoding="utf-8") as f:
        raw_lines = [line.strip() for line in f]
    lines = adjustSub_by_text_similarity(gt_list,raw_lines)
    #make dict
    dict_list = []
    for idx in range(len(lines)):
        script={}
        script['content'] = lines[idx]
        time_raw = raw_lines[idx * 4 +1 ].split(' --> ')
        start = time_raw[0].split(':')
        stop = time_raw[1].split(':')
        script['start'] = float(start[0])*3600 + float(start[1])*60 + float(start[2].replace(',','.'))
        script['stop'] = float(stop[0])*3600 + float(stop[1])*60 + float(stop[2].replace(',','.'))
        dict_list.append(script)
    #merge duplicated sentences
    script_not_dup_list = []
    for idx in range(len(dict_list)):
        dup_list = []
        for idx_inner in range(len(dict_list)):
            if dict_list[idx_inner]['content']==dict_list[idx]['content']:
                dup_list.append(idx_inner)
        for dup_idx in dup_list:
            if dup_idx == min(dup_list):
                dict_list[dup_idx]['type'] = 'lead_sentence'
            else:
                dict_list[dup_idx]['type'] = 'duplicated'
        dict_list[dup_list[0]]['stop'] = dict_list[dup_list[-1]]['stop']
        if dict_list[idx]['type'] == 'lead_sentence':
            script_not_dup_list.append(dict_list[idx])
                
    #avoid subtitle overlapping ?   Timeline overlapping not found currently

    
    #cut by max length---->  eng seperated problem   {eng_idx}
    #ENG counts, zh counts, space counts
    new_idx = 0
    splitted_dict = []
    for dic in dict_list:
        time_ratio, sentences = sentence_time_ratio(dic['content'],13)
        for s in range(len(sentences)):
            new_dict = {}
            new_dict['index'] = new_idx
            start = dic['start']
            for t in range(s):
                start += (dic['duration']*time_ratio[t])
            new_dict['start'] = start
            new_dict['duration'] = dic['duration'] * time_ratio[s]
            new_dict['content'] = sentences[s]
            new_idx+=1
            splitted_dict.append(new_dict)

    return splitted_dict



def adjustSub_by_text_similarity(gts,gens_raw):
    gens = []
    for idx in range(int((len(gens_raw)+1)/4)):
        gens.append(gens_raw[idx*4+2])
    
    combine2 = [''.join([i,j]) for i,j in zip(gts, gts[1:])]
    combine3 = [''.join([i,j,k]) for i,j,k in zip(gts, gts[1:], gts[2:])]
    alls = gts + combine2 + combine3

    adjusted = [None]*len(gens)
    duplicated_list = []
    for idx in range(len(gens)):
        match_text = difflib.get_close_matches(gens[idx], alls, cutoff=0.1)
        if match_text[0] in duplicated_list:
            for mt in match_text:
                if mt == adjusted[idx-1] or mt not in duplicated_list:
                    adjusted[idx] = mt
                    break
        else:
            adjusted[idx] = match_text[0]
            duplicated_list.append(match_text[0])
    return adjusted

def trim_punctuation(s):
    pat_block = u'[^\u4e00-\u9fff0-9a-zA-Z]+';
    pattern = u'([0-9]+{0}[0-9]+)|{0}'.format(pat_block)
    res = re.sub(pattern, lambda x: x.group(1) if x.group(1) else u" " ,s)
    return res

def splitter(s):
    for sent in re.findall(u'[^!?，。\!\?]+[!? 。\!\?]?', s, flags=re.U):
        yield sent

def split_by_pun(s):
    res = list(splitter(s))
    return res
def split_by_word(s):
    slice_size = 3
    paragraph_len = len(s)
    slice_num = int(math.ceil(paragraph_len/slice_size))
    slice_list = []
    for n in range(slice_num):
        slice_list.append(s[n*slice_size:n*slice_size+slice_size])
    return slice_list

raw_str = '更糟糕的是，與大量關注相伴的並非用戶讚賞，而是 Windows 10 on ARM 的不成熟暴露無遺，以及隨之而來的如潮差評──對用戶使用體驗影響最惡劣的，莫過於 Windows 10 on ARM 僅能透過模擬兼容老舊過時的 32 位元 x86 應用，而對效能與普及度俱佳的 64 位元 x86（即 x64）應用無能為力'
sub_dict = parse_script("out.txt",split_by_pun(raw_str))
