import QtQuick 2.15
import QtQuick.Controls.Fusion 6.5 // So we can overload the native style!
import QtQuick.Layouts 1.15
import QtQuick.Effects // required for MultiEffects

import LtgWidgets 1.0

Item {
    width: 750
    height: 325
			
    // Instruction text property
    property string instructionText: 
		"<h3>How to Use the Extra Looper 1 Emulator</h3>
		<p>
		<br>This looper  supports making subsequent loops a multiple of the first loop's length,
		<br>depending on whether <strong>\"Lock to first loop length\"</strong> is checked.
		</p>
		
		<br>To get started, create at least two tracks with input and output(s) configured.
		<br>
		<br>Press the <strong>Loop</strong> button to begin recording.
		<br>Press the button again to stop recording and loop the current section.
		<br>Press the button once more to start a new recording on the same track.
		<br>
		<br>Press the <strong>Change Track</strong> button to select a different track.
		<br>From this point, the <strong>Loop</strong> button will create loops on the selected track.
		<br>
		<br>Pressing the <strong>Pause</strong> button while looping will halt the looper at the end of the current loop. 
		<br>The <strong>Pause</strong> button will turn red and change its label to <strong>Resume</strong>.
		<br>
		<br>Press the <strong>Reset</strong> button to clear the song and reset the looper.
		<br>
		<h4>Using the Looper with a MIDI Pedal or MIDI Controller</h4>
		<p>Right-click on the <strong>Loop</strong> button to assign each button to a MIDI event using the <strong>MIDI Learn</strong> function.</p>"


    // Signal to LoopToGo
    signal ltgExecute(ltgType: string, ltgAction: string, ltgParameters: string)
				
	// Variables from LoopToGo that will be used in this qml file
	Component.onCompleted: {
		loopToGo.registerProperty("lastCreatedRecordLoopColor", "string");
		loopToGo.registerProperty("selectedTrack", "string");
		loopToGo.registerProperty("isPaused", "bool");
		loopToGo.registerProperty("isRecording", "bool");
		loopToGo.registerProperty("trackName1", "string");
		loopToGo.registerProperty("trackName2", "string");
		loopToGo.registerProperty("trackName3", "string");
		loopToGo.registerProperty("trackName4", "string");
		loopToGo.registerProperty("trackColor1", "string");
		loopToGo.registerProperty("trackColor2", "string");
		loopToGo.registerProperty("trackColor3", "string");
		loopToGo.registerProperty("trackColor4", "string");		
		loopToGo.registerProperty("trackNameColor1", "string");
		loopToGo.registerProperty("trackNameColor2", "string");
		loopToGo.registerProperty("trackNameColor3", "string");
		loopToGo.registerProperty("trackNameColor4", "string");
		loopToGo.registerProperty("loopColorAtPlayHead1", "string");
		loopToGo.registerProperty("loopColorAtPlayHead2", "string");
		loopToGo.registerProperty("loopColorAtPlayHead3", "string");
		loopToGo.registerProperty("loopColorAtPlayHead4", "string");
		loopToGo.registerProperty("pUniqueLoopLengthChecked", "bool");
		loopToGo.registerProperty("pDontChangeTrackMonitoring", "bool");
		loopToGo.registerProperty("pNbMaxSecs", "int");

		
		Qt.callLater(() => {
					loopToGo.ltgExecute("scriptCommand", "setLooperMode", "1 1");  // 1 for FreeNoSync, 1 for add to stack
			});
	}
	
	Component.onDestruction: {
		loopToGo.ltgExecute("scriptCommand", "resetLooperMode", "");		
	}
	
	
    // Rectangle as the background
    Rectangle {
		id: mainRectangle
        width: parent.width
        height: parent.height
        color: "#353535"  // Dark background color
		
		// Title
		Text {
			id: titleText
			
			text: "Extra Looper 1"			
			color: "#eeeeee"			
			anchors.top: parent.top	
			anchors.horizontalCenter: parent.horizontalCenter  // Centers the text horizontally			
			anchors.margins: mainRectangle.height*.06	
			font.pixelSize: mainRectangle.width * 0.04
            font.bold: true			
			
		}
				

		// Small Button with Image (Bottom-left corner)
		LtgLogoButton {
			width: 25
			height: width
		}
	    
		// Help Button (Top-right corner)
        LtgHelpButton {
            // Show instructions when clicked
			onClicked: {
				messageWindow.show();
			}
			
			width: 25
			height: width
			
			anchors.left: parent.left // Anchor to the left
			anchors.right: undefined // Ensure it's not anchored to the right
			anchors.top: parent.top // Keep it at the top if needed
			anchors.margins: 10 // Optional margin adjustment
        }

		// Message dialog to display instructions		
		LtgMessageWindow {
			id: messageWindow
			title: "Instructions"
			
		}
		
		LtgButton {
			id: toggleUniqueLoopLength
			
			width: mainRectangle.width*.03
			height: width
			
			ltgType: "loadScript"
			ltgAction: "LoopToGo/togglePersistentVariable.ltgs"
			ltgParameters: "pUniqueLoopLengthChecked"
			
			anchors.bottom: parent.bottom
			anchors.left: parent.left
			anchors.leftMargin: mainRectangle.width*.14
			anchors.bottomMargin: mainRectangle.height*.05
			
			background: Rectangle {
				
				color: loopToGo.properties["pUniqueLoopLengthChecked"] ? "green" : "gray"
				radius: 4
			}
			Text {
				text: "Same as first"
				color: loopToGo.properties["pUniqueLoopLengthChecked"] ? "#EEEEEE" : "#999999"
				font.pixelSize: mainRectangle.width*.02
				verticalAlignment: Text.AlignVCenter
				
				anchors.verticalCenter: toggleUniqueLoopLength.verticalCenter
				anchors.left : toggleUniqueLoopLength.right
				anchors.leftMargin: implicitHeight * 0.7
			}
			
		}
		
		// --- Max Secs Selector ---
        Row {
            spacing: 8
            anchors.bottom: parent.bottom
			anchors.left: parent.left
			anchors.leftMargin: mainRectangle.width*.35
			anchors.bottomMargin: mainRectangle.height*.036

            Text {
                text: "Max nb of secs:"
                color: "#EEEEEE"
                font.pixelSize: mainRectangle.width*.018
                anchors.verticalCenter: parent.verticalCenter
            }

            SpinBox {
                id: barSpinBox
                from: 15
                to: 60
                value: loopToGo.properties["pNbMaxSecs"] !== undefined ? loopToGo.properties["pNbMaxSecs"] : 20
                editable: true
				
				onValueChanged: {
					loopToGo.ltgExecute("scriptCommand", "persistentVariable", "pNbMaxSecs " + value);
				}
                
                // Custom styling to fit your UI
                contentItem: TextInput {
                    text: barSpinBox.textFromValue(barSpinBox.value, barSpinBox.locale)
                    font.pixelSize: mainRectangle.width*.02
                    color: "white"
                    horizontalAlignment: Qt.AlignHCenter
                    verticalAlignment: Qt.AlignVCenter
                }
                background: Rectangle {
                    implicitWidth: 50
                    implicitHeight: 25
                    color: "#444444"
                    border.color: "#888888"
                    radius: 4
                }
            }
        }
		
		LtgButton {
			id: toggleChangeTrackMonitoring
			
			width: mainRectangle.width*.03
			height: width
			
			ltgType: "loadScript"
			ltgAction: "LoopToGo/togglePersistentVariable.ltgs"
			ltgParameters: "pDontChangeTrackMonitoring"
			
			anchors.bottom: parent.bottom
			anchors.left: parent.left
			anchors.leftMargin: mainRectangle.width*.61
			anchors.bottomMargin: mainRectangle.height*.05
			
			background: Rectangle {
				
				color: loopToGo.properties["pDontChangeTrackMonitoring"] ? "green" : "gray"
				radius: 4
			}
			Text {
				text: "Preserve monitoring"
				color: loopToGo.properties["pDontChangeTrackMonitoring"] ? "#EEEEEE" : "#999999"
				font.pixelSize: mainRectangle.width*.02
				verticalAlignment: Text.AlignVCenter
				
				anchors.verticalCenter: toggleChangeTrackMonitoring.verticalCenter
				anchors.left : toggleChangeTrackMonitoring.right
				anchors.leftMargin: implicitHeight * 0.7
			}
			
		}		
		
		

		ColumnLayout {
																		
			width: parent.width * 0.92 // Set width to % of the parent's width
			height: parent.height // Maintain full height
			anchors.left: parent.left // Align to the left
			anchors.right: undefined
			anchors.top: parent.top // Keep the top anchor if needed
			anchors.bottom: parent.bottom // Keep bottom alignment if required

			//spacing: mainRectangle.height * 0.00005
			anchors.margins: -mainRectangle.width * 0.025
			//anchors.leftMargin: mainRectangle.width * 0.00005
			anchors.topMargin: mainRectangle.height * 0.30
			anchors.bottomMargin: mainRectangle.height * 0.15

			
			Item {  // First row
				id: loopersItem1
				
				Layout.fillWidth: true
				Layout.fillHeight: true  // Make it resizable

				property bool isValidColor: loopToGo.properties 
					&& loopToGo.properties["lastCreatedRecordLoopColor"] !== undefined

				property string recordLoopColor: isValidColor 
					 ? (loopToGo.properties["lastCreatedRecordLoopColor"] === "0" 
						? "#000000" 
						: loopToGo.properties["lastCreatedRecordLoopColor"]) 
					 : "#000000"

				RowLayout {
						anchors.fill: parent
						spacing: mainRectangle.height*.004
						anchors.margins: mainRectangle.height*.12	
						//anchors.leftMargin: mainRectangle.width*.1	
						//anchors.rightMargin: mainRectangle.width*.2	

					Repeater {
						model: 4 // Repeat 4 times
						delegate: Item {
							Layout.fillWidth: true
							Layout.fillHeight: true

							property string loopColorAtPlayHead: "loopColorAtPlayHead" + (index + 1)
							property string trackName: "trackName" + (index + 1)

							Rectangle {
								width: selectTrackButton.width * 0.84
								height: selectTrackButton.height * 0.2
								anchors.centerIn: parent
								anchors.verticalCenterOffset: -selectTrackButton.height * 0.7
								color: ((loopToGo.properties[loopColorAtPlayHead] !== undefined) &&
										(loopToGo.properties[loopColorAtPlayHead] !== "0")) 
										? loopToGo.properties[loopColorAtPlayHead] 
										: "black"
								radius: 8
							}

							Rectangle {
								width: selectTrackButton.width + 8
								height: selectTrackButton.height + 8
								anchors.centerIn: parent
								color: ((loopToGo.properties["selectedTrack"] !== undefined) &&
										(loopToGo.properties["selectedTrack"] === loopToGo.properties[trackName])) 
										? "white" 
										: "black"
								radius: 15
							}

							LtgButton {
								id: selectTrackButton
								text: (loopToGo.properties[trackName] !== "0" && loopToGo.properties[trackName] !== undefined) 
									  ? loopToGo.properties[trackName] 
									  : ""
								palette.buttonText: (loopToGo.properties["trackNameColor" + (index + 1)] === "0" || 
													loopToGo.properties["trackNameColor" + (index + 1)] === undefined) 
													? "white" 
													: loopToGo.properties["trackNameColor" + (index + 1)]

								ltgType: "shortcut"
								ltgAction: "shortcut"
								ltgParameters: "Ctrl+" + (index + 1)

								anchors.centerIn: parent
								width: mainRectangle.width * 0.19
								height: mainRectangle.height * 0.2
								font.pixelSize: mainRectangle.width * 0.02

								background: Rectangle {
									property var baseColor: (loopToGo.properties["trackColor" + (index + 1)] === "0" || 
															 loopToGo.properties["trackColor" + (index + 1)] === undefined) 
															 ? "gray" 
															 : loopToGo.properties["trackColor" + (index + 1)]
									color: parent.pressed ? Qt.darker(baseColor, 1.2) : baseColor
									radius: 10
								}
								font.bold: true
							}
						}
					}

					
				}	
			}	

			Item {  // Second row row
				id: loopersItem2
								
				Layout.fillWidth: true
				Layout.fillHeight: true  // Make it resizable
				RowLayout {
							anchors.fill: parent
					spacing: mainRectangle.height * 0.004
					anchors.margins: mainRectangle.height * 0.12

					Repeater {
						model: [
							{
								text: "Record\nPlay",
								type: "loadScript",
								action: "LoopToGo/LooperEmulations/dtPlus.ltgs",
								parameters: "-1 -1 -1 1",
								armEnabled: true, 
								color: "#F44336"
							},
							{
								text: loopToGo.properties["isPaused"] ?
									(loopToGo.properties["isRecording"] ? "Resume" : "Pause\nAt End") :
									(loopToGo.properties["isRecording"] ? "Pause\nAt End" : "Pause\nAt End"),
								type: "loadScript",
								action: "LoopToGo/LooperEmulations/pauseAll.ltgs",
								parameters: "",
								armEnabled: false, 
								color: loopToGo.properties["isRecording"] && loopToGo.properties["isPaused"] ? "green" : "#8450a4"
							},
							{
								text: loopToGo.properties["isPaused"] ?
									(loopToGo.properties["isRecording"] ? "Resume" : "Pause\nNow") :
									(loopToGo.properties["isRecording"] ? "Pause\nNow" : "Pause\nNow"),
								type: "loadScript",
								action: "LoopToGo/LooperEmulations/pauseAll.ltgs",
								parameters: "1",
								armEnabled: false, 
								color: loopToGo.properties["isRecording"] && loopToGo.properties["isPaused"] ? "green" : "#8450a4"
							},
							{
								text: "Undo",
								type: "loadScript",
								action: "LoopToGo/LooperEmulations/undo.ltgs",
								parameters: "",
								armEnabled: false, 
								color: "#FF9800"
							}
						]


						delegate: Item {
							Layout.fillWidth: true
							Layout.fillHeight: true

							LtgButton {
								text: modelData.text
								ltgType: modelData.type
								ltgAction: modelData.action
								ltgParameters: modelData.parameters
								ltgArmEnabled: modelData.armEnabled
								ltgArmScript: "LoopToGo/audioTrigger.ltgs"

								anchors.centerIn: parent
								width: mainRectangle.width * 0.19
								height: mainRectangle.height * 0.2
								font.pixelSize: mainRectangle.width * 0.025

								background: Rectangle {
									color: parent.pressed ? Qt.darker(modelData.color, 1.2) : modelData.color
									radius: 10
								}
								font.bold: true
							}
						}
					}
				}
			}
		}
			
		ColumnLayout {
			
			//width: parent.width // Set width to % of the parent's width
			//height: parent.height // Maintain full height
			anchors.right: parent.right // Align to the right
			anchors.top: parent.top // Keep the top anchor if needed
			anchors.bottom: parent.bottom // Keep bottom alignment if required

			spacing: mainRectangle.height * 0.07
			anchors.margins: mainRectangle.height * 0.01
			anchors.topMargin: mainRectangle.height * 0.1
			anchors.rightMargin: mainRectangle.width * 0.08
			anchors.bottomMargin: mainRectangle.height * 0.1

			
			Repeater {
				model: [
					{ text: "Toggle\nMute\nSelected", type: "shortcut", action: "shortcut", parameters: "Ctrl+T", color: "#1a74ea" },
					{ text: "Toggle\nMute All", action: "LoopToGo/LooperEmulations/toggleMuteAllTracks.ltgs", type: "loadScript", color: "#1a74ea" },
					{ text: "Clear Data\nSelected\nLoop", action: "shortcut", type: "shortcut", parameters: "E", color: "#1a74ea" },
					{ text: "Reset\nSong", action: "LoopToGo/LooperEmulations/resetSong.ltgs", type: "loadScript", color: "#F44336" }
				]

				delegate: Item {
					Layout.fillWidth: true
					Layout.fillHeight: true

					LtgButton {
						text: modelData.text
						ltgType: modelData.type
						ltgAction: modelData.action
						ltgParameters: modelData.parameters ? modelData.parameters : ""

						anchors.centerIn: parent
						width: mainRectangle.width * 0.09
						height: mainRectangle.height * 0.2
						font.pixelSize: mainRectangle.width * 0.013

						background: Rectangle {
							color: parent.pressed ? Qt.darker(modelData.color, 1.2) : modelData.color
							radius: 10
						}
						font.bold: true
					}
				}
			}
		}	
			
	}
}