import {LitElement, html, css} from 'lit';
import {classMap} from 'lit/directives/class-map.js';
import '../rhodecode-unsafe-html/rhodecode-unsafe-html.js';

export class RhodecodeToast extends LitElement {
  static styles = css`
    .absolute-center {
      margin: auto;
      position: absolute;
      top: 0;
      left: 0;
      bottom: 0;
      right: 0;
    }

    .top-left-rounded-corner {
      -webkit-border-top-left-radius: 2px;
      -khtml-border-radius-topleft: 2px;
      border-top-left-radius: 2px;
    }

    .top-right-rounded-corner {
      -webkit-border-top-right-radius: 2px;
      -khtml-border-radius-topright: 2px;
      border-top-right-radius: 2px;
    }

    .bottom-left-rounded-corner {
      -webkit-border-bottom-left-radius: 2px;
      -khtml-border-radius-bottomleft: 2px;
      border-bottom-left-radius: 2px;
    }

    .bottom-right-rounded-corner {
      -webkit-border-bottom-right-radius: 2px;
      -khtml-border-radius-bottomright: 2px;
      border-bottom-right-radius: 2px;
    }

    .top-left-rounded-corner-mid {
      -webkit-border-top-left-radius: 2px;
      -khtml-border-radius-topleft: 2px;
      border-top-left-radius: 2px;
    }

    .top-right-rounded-corner-mid {
      -webkit-border-top-right-radius: 2px;
      -khtml-border-radius-topright: 2px;
      border-top-right-radius: 2px;
    }

    .bottom-left-rounded-corner-mid {
      -webkit-border-bottom-left-radius: 2px;
      -khtml-border-radius-bottomleft: 2px;
      border-bottom-left-radius: 2px;
    }

    .bottom-right-rounded-corner-mid {
      -webkit-border-bottom-right-radius: 2px;
      -khtml-border-radius-bottomright: 2px;
      border-bottom-right-radius: 2px;
    }

    .alert {
      clear: both;
      padding: 15px;
      margin: 10px 0;
      border: 1px solid;
      border-radius: 2px;
      color: #7E7F7F;
      border-color: #84a5d2;
      background-color: #e6edf6;
    }

    .alert-success {
      border-color: #0ac878;
      background-color: #daf7eb;
    }

    .alert-error {
      border-color: #e85e4d;
      background-color: #fbdfdb;
    }

    .alert-warning {
      border-color: #ffc854;
      background-color: #fff4dd;
    }

    .alert-info {
      border-color: #84a5d2;
      background-color: #e6edf6;
    }

    .toast-close {
      margin: 0;
      float: right;
      cursor: pointer;
    }

    .toast-message-holder {
      background: rgba(255, 255, 255, 0.25);
    }

    .toast-message-holder.fixed {
      position: fixed;
      padding: 10px 0;
      margin-left: 10px;
      margin-right: 10px;
      top: 0;
      left: 0;
      right: 0;
      z-index: 100;
    }
  `;

  static properties = {
    toasts: {type: Array},
    isFixed: {type: Boolean}
  };

  constructor() {
    super();
    this.toasts = [];
    this.isFixed = false;
    this._headerNode = null;
    this._debouncedCalcBound = this._debouncedCalc.bind(this);
    this._handleKeyupBound = this._handleKeyup.bind(this);
    this._debounceTimeout = null;
  }

  get hasToasts() {
    return this.toasts && this.toasts.length > 0;
  }

  connectedCallback() {
    super.connectedCallback();
    this._headerNode = document.querySelector('.header');
    window.addEventListener('scroll', this._debouncedCalcBound);
    window.addEventListener('resize', this._debouncedCalcBound);
    window.addEventListener('keyup', this._handleKeyupBound);
    this._debouncedCalc();
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    window.removeEventListener('scroll', this._debouncedCalcBound);
    window.removeEventListener('resize', this._debouncedCalcBound);
    window.removeEventListener('keyup', this._handleKeyupBound);
    if (this._debounceTimeout) {
      clearTimeout(this._debounceTimeout);
    }
  }

  updated(changedProperties) {
    if (changedProperties.has('toasts')) {
      $.Topic('/favicon/update').publish({count: this.toasts.length});
    }
  }

  render() {
    if (!this.hasToasts) {
      return html``;
    }

    return html`
      <div class=${classMap({
        'container': true,
        'toast-message-holder': true,
        'fixed': this.isFixed
      })}>
        ${this.toasts.map((item, index) => html`
          <div class="alert alert-${item.level}">
            <div class="toast-close" @click=${() => this.dismissNotification(index)}>
              <span>${this._gettext('Close')}</span>
            </div>
            <rhodecode-unsafe-html .text=${item.message}></rhodecode-unsafe-html>
          </div>
        `)}
      </div>
    `;
  }

  _handleKeyup(event) {
    if (event.key === 'Escape') {
      this.dismissNotifications();
    }
  }

  _debouncedCalc() {
    if (this._debounceTimeout) {
      clearTimeout(this._debounceTimeout);
    }
    this._debounceTimeout = setTimeout(() => {
      this.toastInWindow();
    }, 25);
  }

  toastInWindow() {
    if (!this._headerNode) {
      return true;
    }
    const headerHeight = this._headerNode.offsetHeight;
    const scrollPosition = window.scrollY;

    if (this.isFixed) {
      this.isFixed = 1 <= scrollPosition;
    } else {
      this.isFixed = headerHeight <= scrollPosition;
    }
  }

  dismissNotification(index) {
    $.Topic('/favicon/update').publish({count: this.toasts.length - 1});
    this.toasts = [
      ...this.toasts.slice(0, index),
      ...this.toasts.slice(index + 1)
    ];
  }

  dismissNotifications() {
    $.Topic('/favicon/update').publish({count: 0});
    this.toasts = [];
  }

  handleNotification(data) {
    if (!templateContext.rhodecode_user.notification_status && !data.message.force) {
      return;
    }
    const newToast = {
      level: data.message.level,
      message: data.message.message
    };
    this.toasts = [...this.toasts, newToast];
  }

  _gettext(x) {
    return _gettext(x);
  }
}

customElements.define('rhodecode-toast', RhodecodeToast);
