import QtQuick 2.0
import QtQuick.Layouts 1.3
import org.kde.plasma.plasmoid 2.0
import org.kde.plasma.core 2.0 as PlasmaCore
import org.kde.kirigami 2.14 as Kirigami

import "./lib/helper.js" as Helper

Item {
  id: main

  property int pollingrate: Plasmoid.configuration.pollingrate
  property int batteryPercent: -2

  PlasmaCore.DataSource {
    id: hsSource
    engine: "executable"
    connectedSources: ["headsetcontrol -bc"]
    interval: pollingrate * 1e3
    onNewData: {
      return batteryPercent = data['exit code'] > 0
        ? -2 // not connected
        : data['stdout'];
    }
  }

  Plasmoid.preferredRepresentation: Plasmoid.compactRepresentation

  Plasmoid.compactRepresentation: Item {
    Layout.minimumWidth: units.iconSizes.medium
    Layout.alignment: Qt.AlignHCenter

    Rectangle { // battery
      id: container
      anchors.fill: parent
      anchors.rightMargin: 2
      anchors.topMargin: 2
      anchors.bottomMargin: 2
      color: "transparent"
      border.color: PlasmaCore.Theme.textColor
      radius: 4
      Plasmoid.toolTipMainText: "battery level: " + Helper.batteryLevel(batteryPercent)
      Plasmoid.toolTipSubText: "polling rate: " + pollingrate + " seconds"

      Item {
        anchors.fill: parent
        anchors.margins: 2
        Rectangle { // battery fill
          anchors.left: parent.left
          anchors.top: parent.top
          anchors.bottom: parent.bottom
          color: Helper.batteryColor(batteryPercent)
          width: parent.width * Math.max(0, Math.min(batteryPercent, 100)) / 100
        }
        Kirigami.Icon { // headphones icon
          anchors.bottom: parent.bottom
          anchors.verticalCenter: parent.verticalCenter
          anchors.horizontalCenter: parent.horizontalCenter
          anchors.topMargin: 1
          anchors.bottomMargin: 1
          source: Helper.batteryIcon(batteryPercent)
        }
      }
    }
    Rectangle { // battery cap
      anchors.left: container.right
      anchors.leftMargin: 1
      anchors.verticalCenter: parent.verticalCenter
      radius: 4
      height: parent.height / 3
      width: 2
      color: PlasmaCore.Theme.textColor
    }
  }
}