-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path2
65 lines (55 loc) · 2.18 KB
/
2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
defmodule ThisWeekendWeb.LocationLive do
alias ThisWeekendWeb.Router.Helpers, as: Routes
use Phoenix.LiveView
alias ThisWeekend.WeatherClient
alias ThisWeekend.{Card, VoteCalculator}
alias ThisWeekendWeb.{Endpoint, Presence}
@topic "this_weekend"
def render(assigns) do
Phoenix.View.render(ThisWeekendWeb.LocationView, "index.html", assigns)
end
def mount(params, socket) do
Endpoint.subscribe(@topic)
assigns = [
step: %{ title: "Step 2", description: "Now that we know what you want to do, where do you want to go?" },
location: nil,
activities: params.activities,
locations: %{},
forecasts: MapSet.new(),
username: params.username,
error: nil
]
{:ok, assign(socket, assigns)}
end
def handle_event("add_location", %{ "location" => %{ "location" => location }}, socket) do
case Geocoder.call(location) do
{ :ok, coordinates } ->
uuid = Ecto.UUID.generate()
Endpoint.broadcast(@topic, "new_location", %{ coordinates: coordinates, uuid: uuid })
locations_map = socket.assigns.locations
|> Map.put_new(uuid, %{ geocode: coordinates })
{ :noreply, assign(socket, locations: locations_map ) }
{ :error, issue} ->
IO.inspect(issue)
{ :noreply, assign(socket, error: "Can't find that location") }
end
end
def handle_info(%{event: "new_location", payload: %{ coordinates: %Geocoder.Coords{ lat: lat, lon: lon }, uuid: uuid }}, socket) do
case WeatherClient.weather(%{lat: Float.to_string(lat), lon: Float.to_string(lon)}) do
{ :ok, weather } ->
{:ok, new_map} = socket.assigns.locations
|> Map.fetch(uuid)
updated_location = new_map
|> Map.merge(%{ weather: Jason.decode!(weather.body) })
IO.inspect(updated_location)
IO.inspect(socket.assigns.locations)
{ :noreply, assign(socket, location: updated_location ) }
{ :error, issue} ->
IO.inspect(issue)
{ :noreply, assign(socket, error: "Can't find weather for that location") }
end
end
def handle_info(%{event: "presence_diff"}, socket) do
{:noreply, assign(socket, users: Presence.list(@topic))}
end
end