import QtQuick 2.7
import Qt5Compat.GraphicalEffects  // For OpacityMask
//import QtGraphicalEffects 1.0

import "../LtgWidgets"

Rectangle {
	id: mainRectangle
    width: 1000
    height: 550
	color: "black"
	
	// List of switches in the image in image coordinates
	property var switchInfo: [
        { x: 305, y: 127, radius: 30, label: "PAUSE", type: "loadScript", action: "LoopToGo/LooperEmulations/pauseAll.ltgs", parameters: ""},
        { x: 465, y: 127, radius: 30, label: "UNDO", type: "shortcut", action: "shortcut", parameters: "Ctrl+Z" },
        { x: 624, y: 127, radius: 30, label: "RESET", type: "loadScript", action: "LoopToGo/LooperEmulations/resetSong.ltgs", parameters: ""},
        { x: 784, y: 127, radius: 30, label: "STOP", type: "loadScript", action: "LoopToGo/LooperEmulations/pauseAll.ltgs", parameters: "1"  },
        { x: 289, y: 362, radius: 30, label: "Track 1", type: "loadScript", action: "LoopToGo/LooperEmulations/dtOne.ltgs", parameters: "1" },
        { x: 459, y: 362, radius: 30, label: "Track 2", type: "loadScript", action: "LoopToGo/LooperEmulations/dtOne.ltgs", parameters: "2" },
        { x: 631, y: 362, radius: 30, label: "Track 3", type: "loadScript", action: "LoopToGo/LooperEmulations/dtOne.ltgs", parameters: "3" },
        { x: 803, y: 362, radius: 30, label: "Track 4", type: "loadScript", action: "LoopToGo/LooperEmulations/dtOne.ltgs", parameters: "4" }
    ]
	
	// List of led in the image in image coordinates
	property var ledInfo: [
        { x: 297, y: 326, radius: 8, colorProperty: "loopColorAtPlayHead1" },
        { x: 462, y: 326, radius: 8, colorProperty: "loopColorAtPlayHead2" },
        { x: 628, y: 326, radius: 8, colorProperty: "loopColorAtPlayHead3" },
        { x: 795, y: 326, radius: 8, colorProperty: "loopColorAtPlayHead4" }
    ]
	
	// 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("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("loopColorAtPlayHead1", "string");
		loopToGo.registerProperty("loopColorAtPlayHead2", "string");
		loopToGo.registerProperty("loopColorAtPlayHead3", "string");
		loopToGo.registerProperty("loopColorAtPlayHead4", "string");
		
		Qt.callLater(() => {
					loopToGo.ltgExecute("scriptCommand", "setLooperMode", "1 1");  // 1 for FreeNoSync, 1 for add to stack
					});
	}
	
	Component.onDestruction: {
		loopToGo.ltgExecute("scriptCommand", "resetLooperMode", "");		
	}
	
    // Bottom image (background)
    Image {
        id: bottomImage
        source: "looperPedalDown.jpg"
        width: parent.width
        height: parent.height
        fillMode: Image.PreserveAspectFit // Keeps aspect ratio while resizing
    }

    // Top image (buttons or interactive layer)
    Image {
        id: topImage
        source: "looperPedalUp.jpg"
        width: parent.width
        height: parent.height
        fillMode: Image.PreserveAspectFit // Keeps aspect ratio while resizing
    }
	
	Rectangle {
		id: rectangleLCDOuter
		width: topImage.paintedWidth*.25
		height: topImage.paintedHeight*.33
		color: "transparent"
		//border.color: "white"
		anchors.centerIn: mainRectangle
		
		Rectangle{
			
			id: rectangleLCD
            width: parent.width*.8
            height: parent.height*.5
			color: "transparent"
			//border.color: "white"
			
            x: parent.width*.1
            y: parent.height*.05
		
			Text {
				id: textLCD
				
				// Dynamically bind each line to properties or variables
				property string line1: "Free Tempo Looper"  // Example dynamic binding
				property string line2: ((loopToGo.properties["selectedTrack"] !== undefined ) &&
						(loopToGo.properties["selectedTrack"] !== "0" ) )? loopToGo.properties["selectedTrack"] : ""  // Another dynamic property
				property string line3: "This line for sale"     // Yet another dynamic property
							
				text: line1 + "\n" + "Selected: " + line2 + "\n" + line3  // Combine the 3 lines with newlines
				
				//text: "This is a \ntest\nline3"
				
				font.pixelSize: topImage.paintedWidth*.02
				font.family: "DS-Digital"
				//color: "darkRed"
				color: "green"
				//horizontalAlignment: Text.AlignHCenter
				//anchors.centerIn: rectangleLCD // Centers the image in the parent item
				
				// Apply 3D effect using only 2D rotation and scale
				transform: [
					Rotation {
						origin.x: rectangleLCD.width/2
						origin.y: rectangleLCD.height/2
					
						axis { x: 1; y: 0; z: 0 }
						angle: 40
					},
					Scale {
						//xScale: 1.0
						yScale: 0.8  // Simulate perspective by scaling vertically
					}
				]
			}
		}
	}

    // Mask 
    Item {
        id: hidingRect
        anchors.fill: bottomImage
        visible: false  // Set to true for debugging

        Rectangle {
			id: rectMask
            
            width: parent.width*.1
            height: width
            radius: width / 2
            color: "yellow"
        }
    }
		
	
	// Dynamic LED (each item creates a LED)
	Repeater {
        model: mainRectangle.ledInfo
		
		Rectangle {
			id: ledRect
            width: modelData.radius * 2 *topImage.paintedWidth *.0007
            height: width
            				
			color: (loopToGo.properties["isRecording"] !== undefined && loopToGo.properties["isRecording"] && loopToGo.properties[modelData.colorProperty] !== undefined) ? loopToGo.properties[modelData.colorProperty] : "#333333"
			radius: width/2
			opacity: 0.5			
			
			// Binding to keep position updated
            property var displayPos: imageToDisplay(modelData.x, modelData.y)
            x: displayPos.x - width / 2
            y: displayPos.y - height / 2
			z: 100 // to make sure it's always on top

            // Ensure position updates on resize
            Connections {
				target: topImage
				function onWidthChanged() { updateLedPosition() }
				function onHeightChanged() { updateLedPosition() }
			}
			// Function to update the position with a slight delay
			function updateLedPosition() {
				Qt.callLater(function() { ledRect.displayPos = imageToDisplay(modelData.x, modelData.y); });
			}
			
			
		}

	}
	
	// Dynamic Buttons (each item creates a LtgButton)
    Repeater {
        model: mainRectangle.switchInfo
        LtgButton {
            id: buttonrect
            width: modelData.radius * 2 *topImage.paintedWidth *.0007
            height: width
            
			// text: modelData.label   // Uncomment this line to see the text button
							
			ltgType: modelData.type
			ltgAction: modelData.action
			ltgParameters: modelData.parameters
			
			background: Rectangle {
				color: "red"
				radius: width/2
				opacity: 0.5
				visible: false   // Comment this line to see the clicking aera
			}

            // Binding to keep position updated
            property var displayPos: imageToDisplay(modelData.x, modelData.y)
            x: displayPos.x - width / 2
            y: displayPos.y - height / 2

            // Ensure position updates on resize
            Connections {
				target: topImage
				function onWidthChanged() { updateButtonPosition() }
				function onHeightChanged() { updateButtonPosition() }
			}
			// Function to update the position with a slight delay
			function updateButtonPosition() {
				Qt.callLater(function() { buttonrect.displayPos = imageToDisplay(modelData.x, modelData.y); });
			}
			
			
			
			MouseArea{
				anchors.fill: parent
				hoverEnabled: true
				
				onEntered: {
					if(index < 4) {
						textLCD.line3 = modelData.label
					} else {
						textLCD.line3 = 
							((loopToGo.properties["trackName" + (index - 3)]) && (loopToGo.properties["trackName" + (index - 3)] != "0"))
							? 
							loopToGo.properties["trackName" + (index - 3)] : ""  // Update line2 text when hovered										
					}
				}	
				onExited: {
					textLCD.line3 = ""
				}

				// Left press handler
				onPressed: {
					
					if (ltgType != "") {
						ltgExecute(ltgType, ltgAction, ltgParameters);
						//console.log(ltgType + " " + ltgAction + " " + ltgParameters)
					}
					
					//console.log("Pressed")
					rectMask.x = displayPos.x - rectMask.width/2		
					rectMask.y = displayPos.y - rectMask.height/2
					theOpacityMask.opacity = 1; // Make the mask visible when pressed
				}
			
				onReleased: {
					//console.log("Released")
					theOpacityMask.opacity = 0; // Hide the mask when released
				}				
			}
			
			// Disable the tooltip
			showToolTip: false  // Hide the tooltip completely
		}
    }
	

    // OpacityMask that applies the mask
    OpacityMask {
		id: theOpacityMask
        anchors.fill: bottomImage
        source: bottomImage
        maskSource: hidingRect		
		opacity: 0		
    }
	
	function imageToDisplay(x, y) {
		// Scale the rectangle size based on the resized image
		
		var scaleX = topImage.paintedWidth/topImage.sourceSize.width
		var scaleY = topImage.paintedHeight/topImage.sourceSize.height
		
		var deltaX = (topImage.width - topImage.paintedWidth)/2
		var deltaY = (topImage.height - topImage.paintedHeight)/2
		
		var displayX =  x*scaleX + deltaX
		var displayY =  y*scaleY + deltaY
		
		//console.log("displayX = " + displayX + ", displayY = " + displayY)
		
		// Update the red rectangle position
		//mask.xImage = displayX
		//mask.yImage = displayY
		
		//theOpacityMask.opacity = 1; // Show the mask when released

		return { x: displayX, y: displayY };
		
	}
	
	function displayToImage(displayX, displayY) {
		// Scale the rectangle size based on the resized image
		var scaleX = topImage.paintedWidth / topImage.sourceSize.width;
		var scaleY = topImage.paintedHeight / topImage.sourceSize.height;

		var deltaX = (topImage.width - topImage.paintedWidth) / 2;
		var deltaY = (topImage.height - topImage.paintedHeight) / 2;

		var imageX = (displayX - deltaX) / scaleX;
		var imageY = (displayY - deltaY) / scaleY;

		//console.log("imageX = " + imageX + ", imageY = " + imageY);

		return { x: imageX, y: imageY };
	}

}
