/** 
 * Render an anchor element that opens an entity form.
 * Uses the context to obtain Xrm variable or tries to obtain it
 * by looking at the parent namespace. An additional onClick will
 * also be called *before* opening the window. Adds "crmLink" to the 
 * the classnames.
 * Props: id, entityName(singular), parameters, windowParameters,
 * openInNewWindow (boolean, default is true, added to windowParmeters if present), className.
 */

import * as React from "react"
const cx = require("classnames")
import { withDynamics, DynamicsContext } from "../Dynamics/Dynamics"
import * as Comp from "../Dynamics/Compatibility"
import { DEBUG } from "BuildSettings"
import { XRM } from "../Dynamics"
import * as PropTypes from "prop-types"

export interface Props {
    entityName: string
    id: string
    openInNewWindow?: boolean
    windowPosition?: number
    height?: number
    width?: number
    onClick?: (e: any) => void
    xrm?: XRM
    className?: string
}

export class EntityLink extends React.Component<Props, any> {

    constructor(props: Props, context: any) {
        super(props, context)
    }

    public context: DynamicsContext

    public static contextTypes = {
        xrm: PropTypes.object
    }

    handleClick = (e: any) => {
        if (this.props.onClick) this.props.onClick(e)

        const xrm: XRM = this.props.xrm || this.context.xrm || (window.parent.Xrm as XRM)
        if (!xrm) {
            if (DEBUG)
                console.log("EntityLink: No Xrm provided in props, context or window parent.")
            return
        }
        const openInNewWindow = this.props.openInNewWindow || true
        const height = this.props.height || 1000
        const width = this.props.width || 1000
        const entityName = this.props.entityName
        const id = this.props.id
        const windowPosition: XrmEnum.WindowPositions = this.props.windowPosition || 2
        const opts = {
            entityName,
            entityId: id ? id : undefined,
            openInNewWindow,
            height,
            width,
            windowPosition,
        }
        if (DEBUG) console.log("EntityLink", opts)
        if (entityName && xrm) xrm.Navigation.openForm(opts, {})
        else console.log("EntityLink: No entityName, id or XRM provided", entityName, id)
    }

    render() {
        const { className, children } = this.props
        return (
            <a href="#"
                className={cx("crmLink", className)}
                onClick={this.handleClick}>
                {children}
            </a>
        )
    }
}

//export const EntityLink = withDynamics(_EntityLink)
//export const EntityLink = _EntityLink

export default EntityLink
