'use strict'

const { TouchBar } = require('electron')
const { TouchBarButton, TouchBarLabel, TouchBarSpacer } = TouchBar

module.exports = function touchBarMenu(window, soundcloud) {

  const nextTrack = new TouchBarButton({
    icon: './app/res/next.png',
    click: () => {
      soundcloud.nextTrack()
    }
  })

  const previousTrack = new TouchBarButton({
    icon: './app/res/previous.png',
    click: () => {
      soundcloud.previousTrack()
    }
  })

  const playPause = new TouchBarButton({
    icon: './app/res/play.png',
    click: () => {
      soundcloud.playPause()
    }
  })

  const likeUnlike = new TouchBarButton({
    icon: './app/res/like.png',
    click: () => {
      soundcloud.likeUnlike()
    }
  })

  const trackInfo = new TouchBarLabel()

  soundcloud.on('play', ({ title, subtitle }) => {
    playPause.icon = './app/res/pause.png'
    // TODO fix this for playlists where subtitle is the playlist title
    trackInfo.label = title + ' by ' + subtitle
  })

  soundcloud.on('pause', () => {
    playPause.icon = './app/res/play.png'
    trackInfo.label = ''
  })

  const touchBar = new TouchBar([
    previousTrack,
    playPause,
    nextTrack,
    likeUnlike,
    new TouchBarSpacer({size: 'flexible'}),
    trackInfo,
    new TouchBarSpacer({size: 'flexible'})
  ])

  window.setTouchBar(touchBar)
}

@@ -114,16 +114,44 @@
 TouchBar
+%0Aconst MAX_TITLE_LENGTH = 38
 %0A%0Amodule
@@ -891,80 +891,8 @@
 ng'%0A
-    // TODO fix this for playlists where subtitle is the playlist title%0A
     
@@ -913,24 +913,26 @@
 l = 
-title + ' by ' +
+formatTitle(title,
  sub
@@ -936,16 +936,17 @@
 subtitle
+)
 %0A  %7D)%0A%0A 
@@ -1257,16 +1257,16 @@
 )%0A  %5D)%0A%0A
-
   window
@@ -1290,8 +1290,403 @@
 hBar)%0A%7D%0A
+%0Afunction formatTitle(title, subtitle) %7B%0A  const titleAndSubtitle = %60$%7Btitle%7D by $%7Bsubtitle%7D%60%0A  if (titleAndSubtitle.length %3E MAX_TITLE_LENGTH)%0A    if (%60$%7Btitle%7D by X%E2%80%A6%60.length %3E MAX_TITLE_LENGTH)%0A      return truncate(title)%0A    else%0A      return truncate(titleAndSubtitle)%0A  else%0A    return titleAndSubtitle%0A%7D%0A%0Afunction truncate(text) %7B%0A  return text.substring(0, MAX_TITLE_LENGTH - 1) + '%E2%80%A6'%0A%7D%0A

Truncate TouchBar song title