module Update.Payment
  ( PaymentAction(..)
  , updatePayment
  ) where

import Date

import Model exposing (Model)
import Model.Payment exposing (..)
import Model.View.PaymentView exposing (..)
import Model.View.Payment.Add exposing (..)

import Update.Payment.Add exposing (..)

type PaymentAction =
  UpdateAdd AddPaymentAction
  | UpdatePayments Payments
  | AddPayment PaymentId String Int
  | ToggleEdit PaymentId
  | Remove PaymentId

updatePayment : Model -> PaymentAction -> PaymentView -> PaymentView
updatePayment model action paymentView =
  case action of
    UpdateAdd addPaymentAction ->
      { paymentView | add <- updateAddPayment addPaymentAction paymentView.add }
    UpdatePayments payments ->
      { paymentView | payments <- payments }
    AddPayment id name cost ->
      let payment =
            { creation = Date.fromTime model.currentTime
            , name = name
            , cost = cost
            , userName = paymentView.userName
            }
      in  { paymentView
          | payments <- addPayment paymentView.payments (id, payment)
          , add <- initAddPayment
          }
    ToggleEdit id ->
      { paymentView | edition <- if paymentView.edition == Just id then Nothing else Just id }
    Remove id ->
      { paymentView | payments <- removePayment paymentView.payments id }