import React from "react";
import { useQuery, useMutation } from "@apollo/react-hooks";
import { gql } from "apollo-boost";
import { GQLWorkspace, GQLChannel } from "./gql-types";

function channelsFirst(a: GQLChannel, b: GQLChannel): number {
  let sameStatus = a.isPrivate == b.isPrivate;
  if (!sameStatus) {
    return a.isPrivate ? 1 : -1;
  }
  return a.name > b.name ? 1 : -1;
}

export default function ChannelList() {
  const { loading, error, data } = useQuery(gql`
    {
      workspace {
        icon
        name
        channels {
          name
          isPrivate
        }
      }
    }
  `);

  const [gotoChat] = useMutation(gql`
    mutation {
      gotoChat(workspace: $workspace, channel: $channel) @client
    }
  `);

  if (loading) {
    return <div>Loading</div>;
  }

  if (error) {
    return <div>{error}</div>;
  }

  return (
    <div>
      {data.workspace.map((ws: GQLWorkspace) => (
        <article key={ws.name} className="workspace">
          <div className="title">
            <img src={ws.icon}></img> {ws.name}
          </div>
          <div className="chats">
            <ul>
              {ws.channels.sort(channelsFirst).map(ch => (
                <li
                  key={ch.name}
                  onClick={a =>
                    gotoChat({
                      variables: { workspace: ws.name, channel: ch.name }
                    })
                  }
                >
                  {ch.name}
                </li>
              ))}
            </ul>
          </div>
        </article>
      ))}
    </div>
  );
}
