/**
 * Prints VRE d4s-social-posts (from @from to @quantity number)
 */
window.customElements.define('d4s-social-posts', class extends HTMLElement {

  #basepath = 'https://api.d4science.org/rest'
  //#basepath = 'https://api.dev.d4science.org/rest'
  #from = 1
  #quantity = 10
  #boot = null
  #data = null
  #shadowRoot = null

  //const url = this.#basepath + '/2/posts/get-posts-vre' // old get, gets all posts unfiltered
  #restRecentPosts = '/2/posts/get-recent-posts-vre-by-range'
  #restComments = '/2/comments/get-comments-by-post-id'

  constructor() {
    super()
    this.#boot = document.querySelector("d4s-boot-2")
    this.#shadowRoot = this.attachShadow({mode: 'open'})
  }

  connectedCallback() {
    if (this.#boot) {
      this.fetchPosts()
    } else {
      console.error('<d4s-boot-2> webcomponent not found in this page')
    }
  }

  fetchPosts() {
    const url = new URL(this.#basepath + this.#restRecentPosts)
    var params = {from: this.#from, quantity: this.#quantity}
    url.search = new URLSearchParams(params).toString()

    this.#boot.secureFetch(url).then(reply => {
      if(reply.status !== 200) throw "status=" + reply.status
      return reply.json()

    }).then(data => {
      //console.log(data)
      this.#data = data
      this.renderPosts()
      //this.rawRenderPosts()

    }).catch(err => console.error("Unable to fetch posts. " + err))
  }

  renderPosts() {
    var ul = document.createElement('ul')
    this.#data.result.posts.forEach(post => {
      var li = document.createElement('li')
      li.id = post.key
      li.classList.add('d4s-social-post')
      const thumbnail = (!post.thumbnail_url.startsWith('http')) ? 'https://' + this.#boot.clientId + post.thumbnail_url : post.thumbnail_url
      const datetime = new Date(0)
      datetime.setUTCMilliseconds(post.time)
      const datetimestr = datetime.toLocaleString()
      li.innerHTML = `
        <div class="d4s-post-heading">
          <div class="d4s-post-avatar">
            <img src="${thumbnail}" onerror="this.style.display='none'" width="32px" height="32px"></slot>
          </div>
          <div class="d4s-post-meta">
            <div class="fullname">${post.full_name}</div>
            <div class="time">${datetimestr}</div>
          </div>
        </div>
        <div class="d4s-post-body">${post.description}</div>
        <div class="d4s-post-footer">
          <div class="comments-nr">${post.comments_no}</div>
          <div class="likes-nr">${post.likes_no}</div>
        </div>
      `
      ul.appendChild(li)

      if (post.comments_no > 0) {
        this.fetchComments(post.key)
      }
    })
    this.#shadowRoot.appendChild(ul)
  }

  rawRenderPosts() {
    var pre = document.createElement('pre')
    console.log(this.#data)
    pre.innerText = JSON.stringify(this.#data, null, " ")
    this.#shadowRoot.appendChild(pre)
  }

  fetchComments(postid) {
    const url = new URL(this.#basepath + this.#restComments)
    var params = {key: postid}
    url.search = new URLSearchParams(params).toString()

    this.#boot.secureFetch(url).then(reply => {
      if(reply.status !== 200) throw "status=" + reply.status
      return reply.json()

    }).then(data => {
      this.renderComments(postid, data)

    }).catch(err => console.error(`Unable to fetch comments for post ${postid}. ` + err))
  }

  renderComments(postid, comments) {
    console.log(comments)
    var li = this.#shadowRoot.getElementById(postid)
    console.log(li)
    var cul = document.createElement('ul')
    cul.classList.add('d4s-post-comments')
    comments.result.forEach(comment => {
      var cli = document.createElement('li')
      cli.id = comment.feedid
      cli.classList.add('d4s-comment')
      const thumbnail = (!comment.thumbnail_url.startsWith('http')) ? 'https://' + this.#boot.clientId + comment.thumbnail_url : comment.thumbnail_url
      const datetime = new Date(0)
      datetime.setUTCMilliseconds(comment.time)
      const datetimestr = datetime.toLocaleString()
      cli.innerHTML = `
        <div class="d4s-comment-heading">
          <div class="d4s-comment-avatar">
            <img src="${thumbnail}" onerror="this.style.display='none'" width="32px" height="32px"></slot>
          </div>
          <div class="d4s-comment-meta">
            <div class="fullname">${comment.full_name}</div>
            <div class="time">${datetimestr}</div>
          </div>
        </div>
        <div class="d4s-comment-body">${comment.text}</div>
        <div class="d4s-comment-footer">
        </div>
      `
      cul.appendChild(cli)
    })
    li.appendChild(cul)
  }

  static get observedAttributes() {
    return ["url", "from", "quantity"];
  }

  attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue !== newValue) {
      switch (name) {
        case "url":
          this.#basepath = newValue
          break
        case "from":
          this.#from = newValue
          break
        case "quantity":
          this.#quantity = newValue
          break
      }
    }
  }
  
  get url() {
    return this.#basepath
  }

  set url(url) {
    this.#basepath = url
    this.setAttribute("url", url)
  }

  get from() {
    return this.#from
  }

  set from(from) {
    this.#from = from
    this.setAttribute("from", from)
  }

  get quantity() {
    return this.#quantity
  }

  set quantity(quantity) {
    this.#quantity = quantity
    this.setAttribute("quantity", quantity)
  }
})

