import React from "react";
import { connect } from "redux-bundler-react";

class Notification extends React.Component {
  constructor(props) {
    super(props);
    this.remove = this.remove.bind(this);
    this.renderContent = this.renderContent.bind(this);
    this.renderDismissButton = this.renderDismissButton.bind(this);
  }

  componentDidMount() {
    let { autoDismiss, onAdd } = this.props;

    if (autoDismiss === 0) {
      console.log(`didn't set up autodismiss`);
    } else {
      if (!autoDismiss) autoDismiss = 5;
      console.log("should set timeout");
      if (!isNaN(Number(autoDismiss))) {
        window.setTimeout(this.remove, autoDismiss * 1000);
      }
    }
    if (onAdd && typeof onAdd === "function") onAdd(this.props);
  }

  remove() {
    const { doNotificationsDismiss, uid, onRemove } = this.props;
    if (uid) doNotificationsDismiss(uid);
    if (onRemove && typeof onRemove === "function") onRemove(this.props);
  }

  renderContent() {
    const { title, message, children } = this.props;
    if (children) {
      return <>{children}</>;
    } else {
      return (
        <>
          <p>
            <strong>{title}</strong>
          </p>
          <p>{message}</p>
        </>
      );
    }
  }

  renderDismissButton() {
    return (
      <button onClick={this.remove} className="close">
        &times;
      </button>
    );
  }

  render() {
    const { level, position } = this.props;

    let notificationClass = `cm-alert`;
    switch (level) {
      case "success":
        notificationClass += ` cm-alert-success`;
        break;
      case "info":
        notificationClass += ` cm-alert-info`;
        break;
      case "warning":
        notificationClass += ` cm-alert-warning`;
        break;
      case "danger":
        notificationClass += ` cm-alert-danger`;
        break;
      default:
        notificationClass += ` cm-alert-default`;
    }

    return (
      <li
        className={notificationClass}
        style={{ minWidth: "300px" }}
        onClick={this.remove}
      >
        {this.renderDismissButton()}
        {this.renderContent()}
      </li>
    );
  }
}

export default connect("doNotificationsDismiss", Notification);
