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

import sys, math
from PyQt5.QtWidgets import QWidget, QApplication, QSlider, QVBoxLayout, QPushButton
from PyQt5.QtGui import QPainter, QPen, QStaticText
from PyQt5.QtCore import Qt

pos = (300, 300)
size = 300
margin = 10

class Michelson(QWidget):
		
	def __init__(self):
		super().__init__()
		
		self.setGeometry(pos[0], pos[1], size + 20 * 40 + 0, size)
		self.setWindowTitle('Michelson')
		
		self.s = []
		for i in range(0, 20):
			self.s.append(SliderK(self, i))
			self.s[i].setGeometry(size + i*40, margin, 40, size - 2*margin)
		
		self.show()
		
	def paintEvent(self, e):
		qp = QPainter()
		qp.begin(self)
		self.drawGraph(qp)
		qp.end()
		
	def drawGraph(self, qp):
		vmax, v = self.values()
		y0 = (size - 2*margin) / 2 + margin
		yk = (y0 - margin) / vmax if vmax > 0 else 0
		qp.setPen(QPen(Qt.black, 1, Qt.SolidLine))
		qp.drawLine(0, y0, size, y0)
		qp.setPen(QPen(Qt.green, 2, Qt.SolidLine))
		for i in range(0, len(v) - 1):
			qp.drawLine(margin + i, y0 - yk * v[i], margin + i + 1, y0 - yk * v[i+1])
		
	def values(self):
		vmax = 0
		v = []
		x = 0
		dx = 2 * math.pi / (size - 2 * margin)
		while x <= 2 * math.pi:
			y = 0
			for i in range(0, 20):
				y = y + self.s[i].v * math.sin((i + 1) * x)
# 			y = math.sqrt(math.pi * math.pi - (x-math.pi) * (x-math.pi))
			if math.fabs(y) > vmax: vmax = math.fabs(y)
			v.append(y)
			x = x + dx
		return (vmax, v)
	
	
class SliderK(QWidget):
		
	def __init__(self, w, i):
		super().__init__(w)
		
		self.w = w
		self.i = i
		self.init = 0
		self.v = 0
		
		label = QPushButton(str(i+1))
		
		self.val = QPushButton(str(self.init))
		self.val.clicked.connect(self.resetK)
		
		self.sld = QSlider(Qt.Vertical, self.w)
		self.sld.setFocusPolicy(Qt.NoFocus)
		self.sld.setMaximum(20)
		self.sld.setMinimum(-20)		
		self.sld.setValue(self.init)
		self.sld.valueChanged[int].connect(self.changeK)
		
		vbox = QVBoxLayout()
		
		vbox.addWidget(label)
		vbox.addWidget(self.val)
		vbox.addWidget(self.sld)
		
		self.setLayout(vbox)
	
	def changeK(self, v):
# 		print("changeK({})={}".format(self.i, v))
		self.v = v
		self.val.setText(str(v))
		self.w.update()
		
	def resetK(self):
		self.sld.setValue(self.init)
	
			
if __name__ == '__main__':	
	app = QApplication(sys.argv)
	widget = Michelson()
	sys.exit(app.exec_())
