import React, { AnchorHTMLAttributes, MouseEvent, useContext } from 'react';

import { RouterContext } from './Router';

type LinkProps = {
    to: string;
} & AnchorHTMLAttributes<any>;

/**
 * This is responsible for converting clicks on links into History Push events
 */
export const Link: React.FC<LinkProps> = (props) => {
    const { push } = useContext(RouterContext);
    const { to, ...rest } = props;
    const onClick = (e: MouseEvent<any>) => {
        e.preventDefault();
        if (to[0] !== '/') {
            console.error('paths must begin with a `/`');
        } else {
            push(to);
        }
    };
    return (
        <a href={to} {...rest} onClick={onClick}>
            {props.children}
        </a>
    );
};
