#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Carla plugin host
# Copyright (C) 2011-2014 Filipe Coelho <falktx@falktx.com>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of
# the License, or any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# For a full copy of the GNU General Public License see the GPL.txt file

# ------------------------------------------------------------------------------------------------------------
# Imports (Config)

from carla_config import *

# ------------------------------------------------------------------------------------------------------------
# Imports (Global)

if config_UseQt5:
    from PyQt5.QtCore import QEvent
    from PyQt5.QtWidgets import QLabel, QTabWidget
else:
    from PyQt4.QtCore import QEvent
    from PyQt4.QtGui import QLabel, QTabWidget

# ------------------------------------------------------------------------------------------------------------
# Imports (Custom Stuff)

from carla_host import *
from carla_patchbay import CarlaPatchbayW
from carla_rack import CarlaRackW

# ------------------------------------------------------------------------------------------------------------
# Tab widget (rack + patchbay)

class CarlaMultiW(QTabWidget):
    def __init__(self, parent, host):
        QTabWidget.__init__(self, parent)

        if False:
            # kdevelop likes this :)
            host = CarlaHostMeta()
            self.host = host

        # -------------------------------------------------------------

        self.fRack     = CarlaRackW(parent, host, False)
        self.fPatchbay = CarlaPatchbayW(parent, host, False, False)
        self.fParent   = parent

        self.fUseCustomPaint = parent.getSavedSettings()[CARLA_KEY_CUSTOM_PAINTING]

        self.addTab(self.fRack, "Plugins")
        self.addTab(self.fPatchbay, "Patchbay")

        #self.fPatchbay.hide()
        #self.removeTab(1)
        #self.fPatchbay.setParent(None)
        #self.fPatchbay.setWindowTitle(parent.windowTitle())
        #self.fPatchbay.show()

        self.scene = self.fPatchbay.scene

        parent.ui.act_plugins_enable.triggered.connect(self.fRack.slot_pluginsEnable)
        parent.ui.act_plugins_disable.triggered.connect(self.fRack.slot_pluginsDisable)
        parent.ui.act_plugins_volume100.triggered.connect(self.fRack.slot_pluginsVolume100)
        parent.ui.act_plugins_mute.triggered.connect(self.fRack.slot_pluginsMute)
        parent.ui.act_plugins_wet100.triggered.connect(self.fRack.slot_pluginsWet100)
        parent.ui.act_plugins_bypass.triggered.connect(self.fRack.slot_pluginsBypass)
        parent.ui.act_plugins_center.triggered.connect(self.fRack.slot_pluginsCenter)
        parent.ui.act_plugins_panic.triggered.connect(self.fRack.slot_pluginsDisable)

        parent.ui.act_canvas_show_internal.triggered.connect(self.fPatchbay.slot_canvasShowInternal)
        parent.ui.act_canvas_show_external.triggered.connect(self.fPatchbay.slot_canvasShowExternal)
        parent.ui.act_canvas_arrange.triggered.connect(self.fPatchbay.slot_canvasArrange)
        parent.ui.act_canvas_refresh.triggered.connect(self.fPatchbay.slot_canvasRefresh)
        parent.ui.act_canvas_zoom_fit.triggered.connect(self.fPatchbay.slot_canvasZoomFit)
        parent.ui.act_canvas_zoom_in.triggered.connect(self.fPatchbay.slot_canvasZoomIn)
        parent.ui.act_canvas_zoom_out.triggered.connect(self.fPatchbay.slot_canvasZoomOut)
        parent.ui.act_canvas_zoom_100.triggered.connect(self.fPatchbay.slot_canvasZoomReset)
        parent.ui.act_canvas_print.triggered.connect(self.fPatchbay.slot_canvasPrint)
        parent.ui.act_canvas_save_image.triggered.connect(self.fPatchbay.slot_canvasSaveImage)

        # TODO, later
        parent.ui.act_canvas_arrange.setEnabled(False)

        parent.ui.act_settings_configure.triggered.connect(self.fPatchbay.slot_configureCarla)

    # -----------------------------------------------------------------
    # HostWidgetMeta methods

    def removeAllPlugins(self):
        self.fRack.removeAllPlugins()
        self.fPatchbay.removeAllPlugins()

    def engineStarted(self):
        self.fRack.engineStarted()
        self.fPatchbay.engineStarted()
        self.fParent.engineStarted()

    def engineStopped(self):
        self.fRack.engineStopped()
        self.fPatchbay.engineStopped()
        self.fParent.engineStopped()

    def idleFast(self):
        self.fRack.idleFast()
        self.fPatchbay.idleFast()

    def idleSlow(self):
        self.fRack.idleSlow()
        self.fPatchbay.idleSlow()

    def projectLoadingStarted(self):
        self.fRack.projectLoadingStarted()
        self.fPatchbay.projectLoadingStarted()

    def projectLoadingFinished(self):
        self.fRack.projectLoadingFinished()
        self.fPatchbay.projectLoadingFinished()

    def saveSettings(self, settings):
        self.fRack.saveSettings(settings)
        self.fPatchbay.saveSettings(settings)

    def showEditDialog(self, pluginId):
        self.fRack.showEditDialog(pluginId)

    # -----------------------------------------------------------------

    def fixCanvasPreviewSize(self):
        self.fPatchbay.resize(self.fRack.size())
        self.fPatchbay.slot_miniCanvasCheckSize()

    # -----------------------------------------------------------------

    def paintEvent(self, event):
        QTabWidget.paintEvent(self, event)

        if MACOS or not self.fUseCustomPaint:
            return

        painter = QPainter(self)
        painter.setBrush(QColor(36, 36, 36))
        painter.setPen(QColor(62, 62, 62))
        painter.drawRect(1, self.height()/2, self.width()-3, self.height()-self.height()/2-1)

    def resizeEvent(self, event):
        QTabWidget.resizeEvent(self, event)

        if self.currentIndex() == 0:
            self.fixCanvasPreviewSize()

# ------------------------------------------------------------------------------------------------------------
# Main Window

class CarlaHostW(HostWindow):
    def __init__(self, host):
        HostWindow.__init__(self, host)

        # -------------------------------------------------------------
        # Set-up container

        self.fContainer = CarlaMultiW(self, host)
        self.setupContainer(True, self.fContainer.fPatchbay.themeData)

        # -------------------------------------------------------------
        # Set-up GUI stuff

        self.fInfoText  = ""
        self.fInfoLabel = QLabel(self)
        self.fInfoLabel.setAlignment(Qt.AlignRight|Qt.AlignVCenter)
        self.fInfoLabel.setText("Engine stopped")

        self.fDockLocation = Qt.LeftDockWidgetArea
        self.fDockFloating = 0

        if MACOS and False: # TODO: check if NOT using pro theme
            self.fInfoLabel.hide()
            self.setUnifiedTitleAndToolBarOnMac(True)

        # -------------------------------------------------------------

        self.ui.act_settings_show_toolbar.triggered.connect(self.slot_toolbarShown)
        self.ui.dockWidget.dockLocationChanged.connect(self.slot_dockLocationChanged)
        self.ui.dockWidget.topLevelChanged.connect(self.slot_dockTopLevelChanged)

        self.ui.dockWidget.installEventFilter(self)

        QTimer.singleShot(0, self.slot_initWidgets)

    # -----------------------------------------------------------------

    def engineChanged(self):
        self.fInfoText = "Engine running | SampleRate: %g | BufferSize: %i" % (self.host.get_sample_rate(), self.host.get_buffer_size())
        self.fInfoLabel.setText("%s | %s" % (self.fInfoText, self.fTransportText))

    def engineStarted(self):
        self.engineChanged()

    def engineStopped(self):
        self.fInfoText = ""
        self.fInfoLabel.setText("Engine stopped")

    # -----------------------------------------------------------------

    def updateInfoLabelXandSize(self):
        tabBar = self.fContainer.tabBar()
        x      = tabBar.width() + 20
        width  = self.fContainer.width() - tabBar.width() - 20

        if self.fDockLocation == Qt.LeftDockWidgetArea and self.fDockFloating <= 1:
            x += self.ui.dockWidget.width()

        self.fInfoLabel.move(x, self.fInfoLabel.y())
        self.fInfoLabel.resize(width, self.fInfoLabel.height())

        if self.fDockFloating == 1:
            self.fDockFloating = 2

    def updateInfoLabelY(self):
        tabBar = self.fContainer.tabBar()
        y = tabBar.mapFromParent(self.ui.centralwidget.pos()).y()

        if not self.ui.toolBar.isVisible():
            y -= self.ui.toolBar.height()

        self.fInfoLabel.move(self.fInfoLabel.x(), y)

    # -----------------------------------------------------------------

    @pyqtSlot()
    def slot_initWidgets(self):
        tabBar = self.fContainer.tabBar()
        x = tabBar.width() + 20
        y = tabBar.mapFromParent(self.ui.centralwidget.pos()).y()

        if self.fDockLocation == Qt.LeftDockWidgetArea and self.fDockFloating <= 1:
            x += self.ui.tabUtils.width()

        self.fInfoLabel.move(x, y)
        self.fInfoLabel.resize(self.fContainer.width()-tabBar.width()-20, tabBar.height())

        # FIXME: Qt4 needs this so it properly creates & resizes the canvas
        self.fContainer.setCurrentIndex(1)
        self.fContainer.setCurrentIndex(0)
        self.fContainer.fixCanvasPreviewSize()

    @pyqtSlot(bool)
    def slot_dockTopLevelChanged(self, top):
        self.fDockFloating = 1 if top else 0
        self.updateInfoLabelXandSize()

    @pyqtSlot(Qt.DockWidgetArea)
    def slot_dockLocationChanged(self, area):
        self.fDockLocation = area
        self.updateInfoLabelXandSize()

    @pyqtSlot()
    def slot_toolbarShown(self):
        self.updateInfoLabelY()

    # -----------------------------------------------------------------

    def eventFilter(self, obj, event):
        if obj == self.ui.dockWidget and event.type() == QEvent.Resize:
            self.updateInfoLabelXandSize()
        return HostWindow.eventFilter(self, obj, event)

    #def closeEvent(self, event):
        #HostWindow.closeEvent(self, event)
        ## needed if using separate patchbay window
        #QApplication.instance().quit()

    def resizeEvent(self, event):
        HostWindow.resizeEvent(self, event)
        self.updateInfoLabelXandSize()

    def timerEvent(self, event):
        HostWindow.timerEvent(self, event)

        if event.timerId() == self.fIdleTimerFast:
            self.fInfoLabel.setText("%s | %s" % (self.fInfoText, self.fTransportText))

# ------------------------------------------------------------------------------------------------------------
# Main

if __name__ == '__main__':
    # -------------------------------------------------------------
    # Read CLI args

    initName = os.path.basename(__file__) if ("__file__" in dir() and os.path.dirname(__file__) in PATH) else sys.argv[0]
    libPrefix = None

    for arg in sys.argv:
        if arg.startswith("--with-appname="):
            initName = os.path.basename(arg.replace("--with-initname=", ""))

        elif arg.startswith("--with-libprefix="):
            libPrefix = arg.replace("--with-libprefix=", "")

    # -------------------------------------------------------------
    # App initialization

    app = CarlaApplication("Carla2", libPrefix)

    # -------------------------------------------------------------
    # Set-up custom signal handling

    setUpSignals()

    # -------------------------------------------------------------
    # Init host backend

    host = initHost(initName, libPrefix, False, False, True)
    loadHostSettings(host)

    # -------------------------------------------------------------
    # Create GUI

    gui = CarlaHostW(host)

    # -------------------------------------------------------------
    # Load project file if set

    args = app.arguments()

    if len(args) > 1:
        arg = args[-1]

        if arg.startswith("--with-appname=") or arg.startswith("--with-libprefix="):
            pass
        elif os.path.exists(arg):
            gui.loadProjectLater(arg)

    # -------------------------------------------------------------
    # Show GUI

    gui.show()

    # -------------------------------------------------------------
    # App-Loop

    app.exit_exec()
