#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#author:Wos
#easy to convert subtitle from vtt to srt
import os
import sys
def vttsrt(vttname):
    try:
        subl = []
        subl_ = []
        idx = 0
        cnt = 0
        if not os.path.exists(vttname):
            print("vtt file doesn't exists!")
            return
        else:
            print("Converting to srt subtitles...")
            f = open(vttname,"r",encoding="utf-8")
            s = f.read()
            f.close()
            subl = str(s).split("\n")
            for i in subl:
                if str(i).strip() == '1':
                    idx = subl.index(i)
                    break
                else:
                    if cnt > 30:
                        srtname = os.path.basename(vttname).split(".")[0]+".srt"
                        command = ("cp %s %s"%(vttname,srtname))
                        os.system(command)
                        return
                    else:
                        cnt += 1
                        continue

            for i in subl[idx:]:
                if "position:" in str(i).strip():
                    subl_.append(str(i).split("position:")[0].strip())
                elif "‎" in str(i).strip():
                    subl_.append(str(i).split("&lrm;")[1].split("</c")[0].strip())
                elif "parent>" in str(i).strip():
                    subl_.append(str(i).split("parent>")[1].split("</c")[0].strip())
                elif "<c.simplifiedchinese>" in str(i).strip():
                    subl_.append(str(i).split("<c.simplifiedchinese>")[1].split("</c.simplifiedchinese>")[0].strip())
                else:
                    subl_.append(str(i))

            srtname = os.path.basename(vttname).split(".")[0]+".srt"
            f = open(srtname,'w',encoding='utf-8').close()
            f = open(srtname,'a',encoding='utf-8')
            for k in subl_:
                f.writelines(str(k)+" \n")
            f.close()
            print("Subtitle conversion complete!")
    except:
        print("Subtitle conversion failed")
        pass


def usage():
    print(os.path.basename(__file__)+" [vtt_filename]")

if __name__ == '__main__':
    try:
        if os.path.exists(sys.argv[1]) and len(sys.argv) == 2:
            vttsrt(sys.argv[1])
        else:
            usage()
    except:
        usage()