{- | CGI program for calculating SNPs
   output:
 0) a pairwise check of equality
 1) a table of variable positions
 2) any other variable columns
 3) ...
-}

import Network.CGI
import Columns
import Data.Char (isDigit)

-- | predefined polymorphic locations
snp_columns :: [Int]
snp_columns = [-21, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 --, 13I, 13II, 13III, 13IV, 13V, 13VI
              , 14, 15, 16, 19, 62, 78, 89, 107, 117, 134, 145, 172
              , 205, 207, 208, 214, 217, 218, 219, 250, 252, 265, 271, 272, 273, 289, 298
              ] 

main :: IO ()
main = runCGI $ handleErrors cgiMain

cgiMain = do m <- getInput "alignment"
             case m of 
               Just n  -> let r = form ++ genResult n
                          in if r/=r then error "Aiieee" else output $ html r
               Nothing -> output $ html form

-- replaces: alignCols . showCols
formatCols :: [String] -> [((Int,Char), [Char])] -> String
formatCols names cols = tabulate (hs:rows)
    where (hs:rows) = showCols names cols
          tabulate (h:rs) = table (tr th h ++ concatMap (tr td) rs)
          table t = "<table>\n"++t++"</table>"
          th, td :: String -> String -> String
          th t x  = "<th style=\"background-color: "++color x++"\">"++t++"</th>"
          td t x  = "<td style=\"background-color: "++color x++"\">"++t++"</td>"
          tr :: (String -> String -> String) -> [String] -> String
          tr c cs = "<tr>"++concat (zipWith c cs hs)++"</tr>\n"
          color x = case reads x of
                      [] -> "#FFFFFF"
                      (n,_):_ -> if n `elem` snp_columns then "#AFFFAF" else "#FFFFFF"

genResult s = 
    let (hs,ss) = unzip $ map splitLine $ drop 1 $ lines s
        cols = transpose ss
    in "<h1>Polymorphic columns</h1>\n"++ 
       (formatCols hs $ filterCols snp_columns $ enumerate (last ss) cols)++ "\n"

form = "<h1>Paste your alignment below:</h1>\n" ++
       "<form method='post' enctype='multipart/form-data'>\n" ++
       "<textarea rows='30' cols='120' name='alignment'></textarea><br />\n" ++
       "<input type='submit' /></form>\n"

html c = "<html><head><title>Alignment analyzer</title></head><body>\n" ++ c ++"</body></html>\n"

