module Main where

import Data.Char (isSpace)
import Data.List (intersperse, break)
import Text.Printf (printf)

main :: IO ()
main = interact labels2vtt

labels2vtt :: String -> String
labels2vtt input = webVtt
  where
    webVtt = unlines $ "WEBVTT" : "" : cues
    cues = map (showVttCue . readLabel) labels
    labels = lines input

readLabel :: String -> (Double, Double, String)
readLabel label = (read start, read end, text)
  where
    (start, rest) = firstWord label
    (end, text) = firstWord rest

firstWord :: String -> (String, String)
firstWord str = (first, drop 1 rest)
  where
    (first, rest) = break isSpace str

showVttCue :: (Double, Double, String) -> String
showVttCue (begin, end, text) =
  unlines [unwords [timecode begin, "-->", timecode end], text]

timecode :: Double -> String
timecode t =
    join ":" [hh, mm, join "." [ss, ms]]
  where
    join sep = concat . intersperse sep
    hh = printf "%02d" $ (secs `div` (60 * 60) :: Int)
    mm = printf "%02d" $ (secs `div` 60 `rem` 60 :: Int)
    ss = printf "%02d" $ (secs `rem` 60 :: Int)
    ms = printf "%03d" $ (truncate $ 1000 * mils :: Int)
    (secs, mils) = properFraction t
