#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# MusE external midi processing script
# By: Staffan Melin 2020 (based on scripts by Robert Jonsson 2009/2012)
# CreateBassline
#=============================================================================
#  MusE
#  Linux Music Editor
#  $Id:$
#
#  Copyright (C) 2002-2011 by Werner Schweer and others
#
#  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 (at your option) 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.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the
#  Free Software Foundation, Inc.,
#  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#=============================================================================


import sys,time
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QComboBox, QPushButton, QGridLayout, QLineEdit

class CreateBassline(QWidget):
	def __init__(self, parent=None):
		QWidget.__init__(self, parent)

		self.setWindowTitle('Create bassline')

		self.timeEdit = QComboBox()
		self.timeEdit.addItem('1/1',1)
		self.timeEdit.addItem('1/2',2)
		self.timeEdit.addItem('1/4',4)
		self.timeEdit.addItem('1/8',8)
		self.timeEdit.addItem('1/16',16)
		self.timeEdit.addItem('1/32',32)
		self.timeEdit.setCurrentIndex(3)
		
		self.gateLengthEdit = QLineEdit()
		self.gateLengthEdit.setText('50')

		self.bassNoteEdit = QLineEdit()
		self.bassNoteEdit.setText('36')

		button = QPushButton("Execute")
		button.clicked.connect(self.execute)

		grid = QGridLayout()
		grid.setSpacing(3)

		grid.addWidget(QLabel('Interval'), 1, 0)
		grid.addWidget(self.timeEdit, 1, 1)

		grid.addWidget(QLabel('Length (% of interval)'), 2, 0)
		grid.addWidget(self.gateLengthEdit, 2, 1)

		grid.addWidget(QLabel('Note (MIDI #)'), 3, 0)
		grid.addWidget(self.bassNoteEdit, 3, 1)

		grid.addWidget(button, 4, 1)

		self.setLayout(grid)
		self.resize(200, 100)
		button.setFocus()

	def execute(self):
		print ("Execute")
		testFile = open(sys.argv[1],"r")
		inputEvents = testFile.readlines()
		testFile.close()
		
		beatDiv = self.timeEdit.itemData(self.timeEdit.currentIndex())
		gateLength = int(self.gateLengthEdit.text())
		bassNote = int(self.bassNoteEdit.text())
		ticksInterval = 384 # default
		partLength = ticksInterval * 4 # default
		outputEvents = []

		# get beat length to calculate length of note
		for line in inputEvents:
			if line.startswith('BEATLEN'):
				tag,tick = line.split(' ')
				ticksInterval = int(int(tick) * 4 / beatDiv) # assumes 4 beats per bar
			if line.startswith('PART'):
				tag,start,end = line.split(' ')
				partLength = int(end) - int(start)

		# loop through events and add old notes
		for line in inputEvents:
			outputEvents.append(line)
		
		noteLength = str(int(ticksInterval * (gateLength / 100)))

		for ticking in range(0, partLength, ticksInterval):
			newline = "NOTE " + str(ticking) + " " + str(bassNote) + " " + noteLength  + " " + "100" + "\n"
			outputEvents.append(newline)
		
		testFile = open(sys.argv[1],"w")
		testFile.writelines(outputEvents)
		testFile.close()

		quit()

app = QApplication(sys.argv)
qb = CreateBassline()
qb.show()
sys.exit(app.exec_())
