open Dash.NET
open Dash.NET.DCC

let neighbourhoods =
    [ "Boston",     ["Back Bay"; "Fenway"; "Jamaica Plain"]
      "London",     ["Canary Wharf"; "Hackney"; "Kensington"]
      "Montreal",   ["Le Plateau"; "Mile End"; "Rosemont"] ]
    |> Map.ofList

let dslLayout = 
    Html.div [
        Attr.children [
            Html.text "Choose a city:"
            Dropdown.dropdown "persisted-city" [
                Dropdown.Attr.value "Montreal"
                Dropdown.Attr.options 
                    ( neighbourhoods
                      |> Map.toList
                      |> List.map fst
                      |> List.map (fun k -> DropdownOption.init(k,k)) )
            ]
            Html.br []

            Html.text "correlated persistence - choose a neighborhood:"
            Html.div [
                Attr.id "neighborhood-container"
                Attr.children [
                    Dropdown.dropdown "neighborhood" []
                ]
            ]
            Html.br []

            Html.div [
                Attr.id "persisted-choices"
            ]
        ]
    ]


let updateDropdown =
    Callback.singleOut(
        [ "persisted-city" @. Value ],
        "neighborhood-container" @. Children,
        fun city ->
            let cityNeighbourhoods = neighbourhoods.Item city
            "neighborhood-container" @. Children => 
                Dropdown.dropdown "neighborhood" [
                    Dropdown.Attr.value cityNeighbourhoods.[0]
                    Dropdown.Attr.options (cityNeighbourhoods |> List.map (fun k -> DropdownOption.init(k,k)))
                    Dropdown.Attr.persistenceType PersistenceTypeOptions.Session
                    Dropdown.Attr.persistence city
                ]
        , PreventInitialCall = false
    )

let updateChoices =
    Callback.singleOut(
        [ "persisted-city" @. Value
          "neighborhood" @. Value ],
        "persisted-choices" @. Children,
        fun city cityNeighbourhood ->
            "persisted-choices" @. Children => sprintf "You chose: %s, %s" cityNeighbourhood city
        , PreventInitialCall = false
    )

[<EntryPoint>]
let main args =
    Giraffe.DashApp.initDefault()
    |> Giraffe.DashApp.withLayout dslLayout
    |> Giraffe.DashApp.addCallback updateDropdown
    |> Giraffe.DashApp.addCallback updateChoices
    |> Giraffe.DashApp.run args (Giraffe.DashGiraffeConfig.initDebug "localhost")