import * as React from "react";
import {RouterState} from "react-router-redux";
import {prefixAll} from "../../react/library/auto-style";
import {BaseComponent, BindThis} from "../../react/stateless-component";
import {ActionTrigger, ReactReduxConnector, TDispatchProps} from "../react-connect";
import {subExtractorOf} from "../virtual-store";
import {IRoutingData, RouteAction, routing, RoutingMethod} from "./redux-router.store";

export interface IALinkProps extends TDispatchProps, React.HTMLProps<HTMLAnchorElement> {
	href: string;
	routeMethod?: RoutingMethod;
	route?: string;
	activeStyle?: React.CSSProperties;
}

const connector = new ReactReduxConnector<any, IALinkProps>();
const mapper = subExtractorOf<RouterState>(routing , 'location');
connector.addMapper((state) => {
	return {route: mapper(state).pathname};
});

@connector.connect
export class ALink extends BaseComponent<IALinkProps> {
	@BindThis
	@ActionTrigger<IRoutingData>(RouteAction)
	private jump(e) {
		e.preventDefault();
		return {
			method: this.props.routeMethod || RoutingMethod.push,
			url: this.props.href,
		} as IRoutingData;
	}
	
	render() {
		let {
			onClick,
			route,
			routeMethod, activeStyle,
			renderCounts, _dispatch,
			href, style,
			...props
		} = this.props;
		const isActive = route === href;
		if (isActive) {
			if (!activeStyle) {
				activeStyle = {cursor: 'default', userSelect: 'none'};
			}
			if (style) {
				style = Object.assign({userSelect: 'none'}, style, activeStyle);
			} else {
				style = activeStyle;
			}
		}
		
		return <a {...props} style={prefixAll(style)} href={isActive? undefined : href} onClick={isActive? undefined : this.jump}/>;
	}
}
