aboutsummaryrefslogtreecommitdiff
path: root/lib/cli/cli.ex
blob: 0402b3f191de4df75053cf414b66993d3c1d0aa2 (plain) (blame)
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
66
67
68
69
70
defmodule SCLI do
  def run() do
    run(nil)
  end

  defp run(pid) do
    nick = Shard.Identity.get_nickname
    prompt = case pid do
      nil -> "(no channel) #{nick}: "
      _ -> 
        {:chat, chan} = GenServer.call(pid, :manifest)
        "##{chan} #{nick}: "
    end

    str = prompt |> IO.gets |> String.trim
    cond do
      str == "/quit" ->
        nil
      String.slice(str, 0..0) == "/" ->
        command = str |> String.slice(1..-1) |> String.split(" ")
        pid2 = handle_command(pid, command)
        run(pid2)
      true -> 
        GenServer.cast(pid, {:chat_send, str})
        run(pid)
    end
  end

  def handle_command(pid, ["connect", ipstr, portstr]) do
    {:ok, ip} = :inet.parse_address (to_charlist ipstr)
    {port, _} = Integer.parse portstr
    SNet.Manager.add_peer(ip, port)
    pid
  end

  def handle_command(pid, ["list"]) do
    IO.puts "List of known channels:"
    list = GenServer.call(Shard.Manager, :list)
    for {_chid, chpid} <- list do
      {:chat, chan} = GenServer.call(chpid, :manifest)
      IO.puts "##{chan}"
    end
    pid
  end

  def handle_command(pid, ["join", qchan]) do
    list = GenServer.call(Shard.Manager, :list)
    list = for {_chid, chpid} <- list,
               {:chat, chan} = GenServer.call(chpid, :manifest),
               do: {chan, chpid}
    case List.keyfind(list, qchan, 0) do
      nil ->
        {:ok, pid} = DynamicSupervisor.start_child(Shard.DynamicSupervisor, {SApp.Chat, qchan})
        pid
      {_, pid} ->
        IO.puts "Switching to ##{qchan}"
        pid
    end
  end

  def handle_command(pid, ["nick", nick]) do
    Shard.Identity.set_nickname nick
    pid
  end

  def handle_command(pid, _cmd) do
    IO.puts "Invalid command"
    pid
  end
end