module PaneMeta exposing (..)

import Data exposing (Id)
import Data.Info exposing (Info)
import Data.Schema exposing (Schema)
import Dict exposing (Dict)
import History exposing (History)
import Network.Messages exposing (ReceiveMessage)
import Time exposing (Zone, Posix)
import List.Extra

init : History -> PaneMeta
init firstEntry =
    { history = [ firstEntry ]
    , schemas = Dict.empty
    , info = Nothing
    , zone = Time.utc
    , zoneName = Nothing
    , now = Time.millisToPosix 0
    , upload = []
    }

type alias PaneMeta =
    { history: List History
    , schemas: Dict String Schema
    , info: Maybe Info
    , zone: Zone
    , zoneName: Maybe String
    , now: Posix
    , upload: List FileUpload
    }

type alias FileUpload =
    { tag: String
    , name: String
    , mime: String
    , person: Id
    , parent: Maybe Id
    , progress: Maybe Float
    }

hasConfidential : String -> PaneMeta -> Bool
hasConfidential database meta =
    Maybe.andThen
        (\info ->
            info.database
            |> List.filter
                ((==) database << .name)
            |> List.head
            |> Maybe.map .hasConfidential
        )
        meta.info
    |> Maybe.withDefault False

pushHistory : History -> PaneMeta -> PaneMeta
pushHistory history meta =
    { meta
    | history = (::) history
        <| List.take 19
        <| List.Extra.unique
        <| List.filter ((/=) history)
            meta.history
    }

apply : ReceiveMessage -> PaneMeta -> PaneMeta
apply event meta =
    case event of
        Network.Messages.InfoSend info ->
            { meta | info = Just info }
        Network.Messages.SchemaResponse name schema ->
            { meta
            | schemas = Dict.insert name schema meta.schemas
            }
        _ -> meta
        