import React from 'react';
import {
  BrowserRouter as Router,
  matchPath,
  useLocation,
} from 'react-router-dom';

const Switch = ({ children: routes }) => {
  const route = useLocation().pathname;
  let realMatch = null;
  const current = Object.entries(routes).find(([path]) => {
    const exact = /^exact /.test(path);
    const match = matchPath(
      route,
      exact ? { exact: true, path: path.slice(6) } : { path }
    );
    if (match) {
      realMatch = match;
      return true;
    }
    return false;
  });
  if (current) {
    const renderable = current[1];
    if (typeof renderable === 'function') {
      return renderable(realMatch);
    }
    return renderable;
  }
  return null;
};