module ServerCommunication ( Communication(..) , sendRequest , serverCommunications ) where import Signal import Task as Task exposing (Task) import Http import Json.Decode exposing (..) import Date import Model.Message exposing (messageDecoder) import Update as U import Update.SignIn exposing (..) import Update.Payment as UP type Communication = NoCommunication | SignIn String | AddPayment String Int | SignOut serverCommunications : Signal.Mailbox Communication serverCommunications = Signal.mailbox NoCommunication sendRequest : Communication -> Task Http.RawError U.Action sendRequest communication = case getRequest communication of Nothing -> Task.succeed U.NoOp Just request -> Http.send Http.defaultSettings request |> Task.map (communicationToAction communication) getRequest : Communication -> Maybe Http.Request getRequest communication = case communication of NoCommunication -> Nothing SignIn login -> Just { verb = "post" , headers = [] , url = "/signIn?login=" ++ login , body = Http.empty } AddPayment name cost -> Just { verb = "post" , headers = [] , url = "/payment/add?name=" ++ name ++ "&cost=" ++ (toString cost) , body = Http.empty } SignOut -> Just { verb = "post" , headers = [] , url = "/signOut" , body = Http.empty } communicationToAction : Communication -> Http.Response -> U.Action communicationToAction communication response = if response.status == 200 then case communication of NoCommunication -> U.NoOp SignIn login -> U.UpdateSignIn (ValidLogin login) AddPayment name cost -> decodeResponse response (\id -> U.UpdatePayment (UP.AddPayment id name cost)) SignOut -> U.GoSignInView else decodeResponse response (\error -> case communication of SignIn _ -> U.UpdateSignIn (ErrorLogin error) _ -> U.NoOp ) decodeResponse : Http.Response -> (String -> U.Action) -> U.Action decodeResponse response responseToAction = case response.value of Http.Text text -> case decodeString messageDecoder text of Ok x -> responseToAction x Err _ -> U.NoOp Http.Blob _ -> U.NoOp