module Main
   where

import IO
import Network
import WeatherData
import ReadForcast
import ReadActual
import ListUtils

--To write out a file after performing an action on streamIn
--Type must be a comment since a must be deduced correctly for read
--writeOut :: String -> ([String] -> [a]) -> String -> IO ()
writeOut file action streamIn = do
 oldContent <- readFile file
 let oldC = read oldContent in
  do
   putStrLn (show (length oldC))
   writeFile file (show (oldC ++ (action (stripToPre (words streamIn)))))

--Writes out the predicted weather
writeOutPredictions :: String -> IO()
writeOutPredictions = 
  writeOut ".storedPredictions" (\ls -> (map predicToTuple (readForcast ls)))

--Reads in predicted weather
readInPredictions :: IO String
readInPredictions = do
 readFile ".storedPredictions"

--Writes out recorded statistics
writeOutActualWeather :: String -> IO()
writeOutActualWeather =
  writeOut ".storedConditions" (\ls -> [(actualToTuple (readActual ls))])

--Reads in predicted weather
readInActualWeather :: IO String
readInActualWeather = do
 readFile ".storedConditions"

--Strips the input string to the <pre> tag, weather data follows this
stripToPre :: [String] -> [String]
stripToPre = stripTo "<pre>"

--Opens a HTTP connection to the specified host and URL and returns the contents
openConnection :: String -> String -> IO String
openConnection connection toGet =
 let pid = connectTo connection 
     s = Service "http" in
   do
    ioh <- pid s
    hSetBuffering ioh NoBuffering
    hPutStr ioh ("Get " ++ toGet ++ " HTTP/1.1" ++ ['\n','\n'])
    s <- hGetContents ioh
    return s
 
main = do
 s1 <- openConnection "www.wrh.noaa.gov" "http:www.wrh.noaa.gov/Saltlake/climate/CLI.shtml"
 s2 <- openConnection "www.wrh.noaa.gov" "http:www.wrh.noaa.gov/Saltlake/forecast/SFT.shtml"

 writeOutActualWeather s1
 writeOutPredictions s2

--Reminder of how to read back in my data
{- predicts <- readInPredictions
 let s = ((read predicts) :: [((Int,String,Int),(Int,String,Int),Int,(Int,Int),Int)]) in 
  do 
   putStrLn (show s) 
 putStrLn (show (actualToTuple (readActual (stripToPre (words s1)))))
-}
