import '@material/web/icon/icon.js'

import gql from 'graphql-tag'
import { css, html, LitElement, nothing } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { connect } from 'pwa-helpers/connect-mixin.js'

import { store } from '@operato/shell'
import { client } from '@operato/graphql'

import { UPDATE_FAVORITES } from '@things-factory/fav-base/client'

@customElement('favorite-tool')
export class FavoriteTool extends connect(store)(LitElement) {
  static styles = css`
    :host {
      display: inline-block;
      vertical-align: middle;
      line-height: 0;
    }

    [favorable] {
      opacity: 0.5;
    }
  `

  @property({ type: Array }) favorites: any[] = []
  @property({ type: Object }) user: any
  @property({ type: String }) resourceId?: string
  @property({ type: Boolean }) favored?: boolean
  @property({ type: Array }) acceptedPages: any[] = []

  page: any

  render() {
    var renderable = (this.acceptedPages || []).indexOf(this.page) !== -1

    return renderable
      ? html`
          <md-icon @click=${this.onClick.bind(this)} ?favorable=${!this.favored}
            >${this.favored ? 'star' : 'star_border'}</md-icon
          >
        `
      : nothing
  }

  updated(changes) {
    if (changes.has('user')) {
      this.refreshFavorites()
    }

    this.favored = (this.favorites || []).includes(this.resourceId)
  }

  stateChanged(state) {
    this.page = state.route.page
    this.favorites = state.favorite.favorites
    this.user = state.auth.user
    this.resourceId = state.route.resourceId
  }

  onClick(event) {
    if (!this.resourceId) {
      return
    }

    if (this.favored) {
      this.removeFavorite(this.resourceId)
    } else {
      this.addFavorite(this.resourceId)
    }
  }

  async refreshFavorites() {
    if (!this.user || !this.user.email) {
      return
    }

    const response = await client.query({
      query: gql`
        query {
          myFavorites {
            id
            routing
          }
        }
      `
    })

    store.dispatch({
      type: UPDATE_FAVORITES,
      favorites: response.data.myFavorites.map(favorite => favorite.routing)
    })
  }

  async removeFavorite(routing) {
    await client.query({
      query: gql`
        mutation {
          deleteFavorite(routing: "${routing}")
        }
      `
    })

    this.refreshFavorites()
  }

  async addFavorite(routing) {
    await client.query({
      query: gql`
        mutation {
          createFavorite(favorite: {
            routing: "${routing}"
          }) {
            id
            routing
          }
        }
      `
    })

    this.refreshFavorites()
  }
}
