import Data.Char (isDigit)
import Data.Foldable (toList)
import Data.List (stripPrefix)
import Data.Maybe (fromJust)
import System.Environment
import System.IO

import Arsec
import CaseFolding
import SpecialCasing
import UnicodeData

main = do
  args <- getArgs
  let oname = case args of
                [] -> "../src/Data/Text/Internal/Fusion/CaseMapping.hs"
                [o] -> o
  psc <- parseSC "SpecialCasing.txt"
  pcf <- parseCF "CaseFolding.txt"
  ud <- parseUD "UnicodeData.txt"
  scs <- case psc of
           Left err -> print err >> return undefined
           Right ms -> return ms
  cfs <- case pcf of
           Left err -> print err >> return undefined
           Right ms -> return ms
  ud <- case ud of
           Left err -> print err >> return undefined
           Right ms -> return ms
  h <- openFile oname WriteMode
  let comments = map ("--" ++) $
                 take 2 (cfComments cfs) ++ take 2 (scComments scs)
      version = parseVersion (cfComments cfs)
  mapM_ (hPutStrLn h) $
                      ["-- AUTOMATICALLY GENERATED - DO NOT EDIT"
                      ,"-- Generated by scripts/CaseMapping.hs"] ++
                      comments ++
                      [""
                      ,"{-# LANGUAGE LambdaCase, MagicHash, PartialTypeSignatures #-}"
                      ,"{-# OPTIONS_GHC -Wno-partial-type-signatures #-}"
                      ,"module Data.Text.Internal.Fusion.CaseMapping where"
                      ,"import GHC.Int"
                      ,"import GHC.Exts"
                      ,"import Data.Version (Version, makeVersion)"
                      ,"unicodeVersion :: Version"
                      ,"unicodeVersion = makeVersion " ++ version
                      ,"unI64 :: Int64 -> _ {- unboxed Int64 -}"
                      ,"unI64 (I64# n) = n"
                      ,""]
  let get f = [(k, d) | c <- toList ud, Just d <- [f c], let k = charUD c, k /= d]
  mapM_ (hPutStrLn h) (mapSC "upper" upper (get toUpperUD) scs)
  mapM_ (hPutStrLn h) (mapSC "lower" lower (get toLowerUD) scs)
  mapM_ (hPutStrLn h) (mapSC "title" title (get toTitleUD) scs)
  mapM_ (hPutStrLn h) (mapCF cfs)
  hClose h

-- Parse version from CaseFolding comments
-- and render it as a list (an argument of makeVersion)
parseVersion :: [String] -> String
parseVersion comments = fromJust $ do
  line' : _ <- pure comments
  line'' <- stripPrefix " CaseFolding-" line'
  let (v1, line1) = span isDigit line''
      (v2, line2) = span isDigit (drop 1 line1)
      (v3, _) = span isDigit (drop 1 line2)
  pure $ "[" ++ v1 ++ ", " ++ v2 ++ ", " ++ v3 ++ "]"
