import React from "react";
import PropTypes from "prop-types";
import Item from "./Item";

function capitalizeChannels(name) {
  if (name == "linkedin") {
    return "LinkedIn";
  }
  return `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
}

function getTabFromRoute(route, channel) {
  const match = route.match(/^.*\/(.*)\/.+$/);
  if (match && match[1]) {
    const currentTab = match[1];
    if (channel.supportedTabs.includes(currentTab)) {
      return currentTab;
    }
  }

  return channel.supportedTabs[0];
}

function findConnection(service, channels) {
  return channels.find((channel) => service === channel.service);
}

const SingleChannel = ({ service, channels, ...props }) => {
  let activeChannel = findConnection(service, channels);
  if (activeChannel) {
    return (
      <Item
        href={`/${activeChannel.service}/${getTabFromRoute(
          props.route,
          activeChannel
        )}/${activeChannel.id}`}
        {...props}
      >
        {capitalizeChannels(activeChannel.service)}
      </Item>
    );
  }
  return (
    <Item href={`/connect/${service}`} {...props}>
      {capitalizeChannels(service)}
    </Item>
  );
};

SingleChannel.defaultProps = {
  channels: [],
  service: "",
};

SingleChannel.propTypes = {
  channels: PropTypes.array,
  service: PropTypes.string,
};

export default SingleChannel;
