# -*- coding: utf-8 -*-
# Author: Ruslan Krenzler.
# 02 December 2017.
# Create 40 and 80 schedule pipes according to NPS standard. 

# For a gui documentation see https://www.freecadweb.org/wiki/PySide_Medium_Examples

from PySide import QtGui, QtCore
import FreeCAD
import Part

# Here are tables for NPS PVC pipe sizes from http://opensourceecology.org/wiki/PVC_Pipe.
# Sizes are in inches. 
# The coums are "Name", "Schedule", "O.D [in]", "Average I.D.[in]",
# "Min. Wall [in]", "Nom.[Wt./Ft.]", "Max. W.P. [PSI])"


NPC_NAME_COLUMN_INDEX = 0
NPC_SCHEDULE_COLUNN_INDEX = 1
NPC_OUTER_DIAMETER_COLUMN_INDEX = 2
NPC_INNER_DIAMETER_COLUMN_INDEX = 3

NPC_PVC_TABLE = [
	['1/8"', 40, 0.405,0.249,0.068,0.051,810],
	['1/4"', 40, 0.540,0.344,0.088, 0.086, 780],
	['3/8"', 40, 0.675, 0.473, 0.091, 0.115, 620],
	['1/2"', 40, 0.840, 0.602, 0.109, 0.170, 600],
	['3/4"', 40, 1.050, 0.804, 0.113, 0.226, 480],
	['1"', 40, 1.315, 1.029, 0.133, 0.333, 450],
	['1-1/4"', 40, 1.660, 1.360, 0.140, 0.450, 370],
	['1-1/2"', 40, 1.900, 1.590, 0.145, 0.537, 330],
	['2"', 40, 2.375, 2.047, 0.154, 0.720, 280],
	['2-1/2"', 40, 2.875, 2.445, 0.203, 1.136, 300],
	['3"', 40, 3.500, 3.042, 0.216, 1.488, 260],
	['3-1/2"', 40, 4.000, 3.521, 0.226, 1.789, 240],
	['4"', 40, 4.500, 3.998, 0.237, 2.118, 220],
	['5"', 40, 5.563, 5.016, 0.258, 2.874, 190],
	['6"', 40, 6.625, 6.031, 0.280, 3.733, 180],
	['8"', 40, 8.625, 7.942, 0.322, 5.619, 160],
	['10"', 40, 10.750, 9.976, 0.365, 7.966, 140],
	['12"', 40, 12.750, 11.889, 0.406, 10.534, 130],
	['1/8"',80, .405, .195, 0.095, 0.063, 1230],
	['1/4"',80, .540, .282, 0.119, 0.105, 1130],
	['3/8"',80, .675, .403, 0.126, 0.146, 920],
	['1/2"',80, .840, .526, 0.147, 0.213, 850],
	['3/4"',80, 1.050, .722, 0.154, 0.289, 690],
	['1"',80, 1.315, .936, 0.179, 0.424, 630],
	['1-1/4"',80, 1.660, 1.255, 0.191, 0.586, 520],
	['1-1/2"',80, 1.900, 1.476, 0.200, 0.711, 470],
	['2"',80, 2.375,1.913, 0.218, 0.984, 400],
	['2-1/2"',80, 2.875, 2.290, 0.276, 1.500, 420],
	['3"',80, 3.500, 2.864, 0.300, 2.010, 370],
	['3-1/2"',80, 4.000, 3.326, 0.318, 2.452, 350],
	['4"',80, 4.500, 3.786, 0.337, 2.938, 320],
	['5"',80, 5.563, 4.768, 0.375, 4.078, 290],
	['6"',80, 6.625, 5.709, 0.432, 5.610, 280],
	['8"',80, 8.625, 7.565, 0.500, 8.522, 250],
	['10"',80, 10.750, 9.493, 0.593, 12.635, 230],
	['12"',80 ,12.750, 11.294, 0.687	,17.384, 230]]

class NpcPVC:
	@staticmethod
	def getUniqueColumnValue(index):
		""" Return a list of column values from
			NPC_PVC_TABLE
			:param index: index of the column.
		"""
		res = [] # Resulting values
		for row in NPC_PVC_TABLE:
			if row[index] not in res:
				res.append(row[index])
		return res

	@staticmethod
	def selectRow(name, sched):
		"""Get a row from the DPC_PVC Table
		:param name: name of the dimension row (pipe size).
		:sched shed: Schedule (pipe wall width)
		:return row from the NPC_PVC table or None if no row fiound.
		"""
		for row in NPC_PVC_TABLE:
			if row[NPC_NAME_COLUMN_INDEX] == name and row[NPC_SCHEDULE_COLUNN_INDEX] == sched:
				return row
		return None

# https://www.freecadweb.org/wiki/Units
tu = FreeCAD.Units.parseQuantity 
def halfKeepTheUnit(val):
	"""Return value val as a string with the half of the value and with thte same unit
	   Example: halfKeepTheUnit("3 in") is '1.5 "'
	"""
	x = tu(val)/2
	unit = x.getUserPreferred()[2]
	return str(x.getValueAs(unit))+unit
	
def createPipe(out_d, in_d, length, name):
	""" A pipe which is a differences of two cilinders: outer cylinder - inner cylinder.
	:param out_d: outer diameter of the pipe
	:param in_d: inner diameter of the pipe
	We try to keep the same unit for the radious of cylinders as in the parameters
	out_d and in_d.
	"""
	# Create outer cylinder.
	outer_cylinder = App.ActiveDocument.addObject("Part::Cylinder","OuterCylinder")
	App.ActiveDocument.recompute()

	# tu(val)/2 will can convert to diffent unit. Therefore we use halfKeepTheUnit() instead.
	outer_cylinder.Radius = halfKeepTheUnit(out_d)
	outer_cylinder.Height = length
	
	# Create inner cylinder.
	inner_cylinder = App.ActiveDocument.addObject("Part::Cylinder", "InnerCylinder")
	App.ActiveDocument.recompute()
	inner_cylinder.Radius = halfKeepTheUnit(in_d)
	inner_cylinder.Height = length
	
	cut = App.activeDocument().addObject("Part::Cut", name)
	cut.Base = outer_cylinder
	cut.Tool = inner_cylinder
	App.ActiveDocument.recompute()

#NpcPVC.getUniqueColumnValue(0)
class AddPvcPipeNpsGuiClass(QtGui.QDialog):
	"""Return index of the row in the NPC_PVC library.
		Return -1 if nothing is selected.
	"""
	def __init__(self):
		super(AddPvcPipeNpsGuiClass, self).__init__()
		self.initUi()
	def initUi(self): 
		Dialog = self # Added 
		self.result = -1 
		self.setupUi(self)
		# Fill schedule and name comboboxes according to NPC_PVC table
		self.initSizes()
		self.restoreRecentInput()
		self.show()

# The next lines are from QtDesigner .ui-file processed by pyside-uic
	def setupUi(self, Dialog):
		Dialog.setObjectName("Dialog")
		Dialog.resize(334, 141)
		self.buttonBox = QtGui.QDialogButtonBox(Dialog)
		self.buttonBox.setGeometry(QtCore.QRect(10, 90, 301, 32))
		self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
		self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Cancel|QtGui.QDialogButtonBox.Ok)
		self.buttonBox.setObjectName("buttonBox")
		self.layoutWidget = QtGui.QWidget(Dialog)
		self.layoutWidget.setGeometry(QtCore.QRect(30, 20, 87, 52))
		self.layoutWidget.setObjectName("layoutWidget")
		self.verticalLayout_2 = QtGui.QVBoxLayout(self.layoutWidget)
		self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
		self.verticalLayout_2.setObjectName("verticalLayout_2")
		self.label = QtGui.QLabel(self.layoutWidget)
		self.label.setObjectName("label")
		self.verticalLayout_2.addWidget(self.label)
		self.comboBoxName = QtGui.QComboBox(self.layoutWidget)
		self.comboBoxName.setObjectName("comboBoxName")
		self.verticalLayout_2.addWidget(self.comboBoxName)
		self.layoutWidget_2 = QtGui.QWidget(Dialog)
		self.layoutWidget_2.setGeometry(QtCore.QRect(130, 20, 87, 52))
		self.layoutWidget_2.setObjectName("layoutWidget_2")
		self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget_2)
		self.verticalLayout.setContentsMargins(0, 0, 0, 0)
		self.verticalLayout.setObjectName("verticalLayout")
		self.label_2 = QtGui.QLabel(self.layoutWidget_2)
		self.label_2.setObjectName("label_2")
		self.verticalLayout.addWidget(self.label_2)
		self.comboBoxSchedule = QtGui.QComboBox(self.layoutWidget_2)
		self.comboBoxSchedule.setObjectName("comboBoxSchedule")
		self.verticalLayout.addWidget(self.comboBoxSchedule)
		self.layoutWidget_3 = QtGui.QWidget(Dialog)
		self.layoutWidget_3.setGeometry(QtCore.QRect(230, 20, 81, 52))
		self.layoutWidget_3.setObjectName("layoutWidget_3")
		self.verticalLayout_3 = QtGui.QVBoxLayout(self.layoutWidget_3)
		self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
		self.verticalLayout_3.setObjectName("verticalLayout_3")
		self.label_3 = QtGui.QLabel(self.layoutWidget_3)
		self.label_3.setObjectName("label_3")
		self.verticalLayout_3.addWidget(self.label_3)
		self.lineEditLength = QtGui.QLineEdit(self.layoutWidget_3)
		self.lineEditLength.setObjectName("lineEditLength")
		self.verticalLayout_3.addWidget(self.lineEditLength)
		
		self.retranslateUi(Dialog)
		QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("accepted()"), Dialog.accept)
		QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL("rejected()"), Dialog.reject)
		QtCore.QMetaObject.connectSlotsByName(Dialog)

	def retranslateUi(self, Dialog):
		Dialog.setWindowTitle(QtGui.QApplication.translate("Dialog", "Dialog", None, QtGui.QApplication.UnicodeUTF8))
		self.label.setText(QtGui.QApplication.translate("Dialog", "Size:", None, QtGui.QApplication.UnicodeUTF8))
		self.label_2.setText(QtGui.QApplication.translate("Dialog", "Schedule:", None, QtGui.QApplication.UnicodeUTF8))
		self.label_3.setText(QtGui.QApplication.translate("Dialog", "Length:", None, QtGui.QApplication.UnicodeUTF8))
		self.lineEditLength.setText(QtGui.QApplication.translate("Dialog", "1ft", None, QtGui.QApplication.UnicodeUTF8))

	def initSizes(self):
		# Get all possible sizes
		scheds = NpcPVC.getUniqueColumnValue(NPC_SCHEDULE_COLUNN_INDEX)
		for sched in scheds:
			self.comboBoxSchedule.addItem(str(sched))
		names = NpcPVC.getUniqueColumnValue(NPC_NAME_COLUMN_INDEX)
		for name in names:
			self.comboBoxName.addItem(name)

	def accept(self):
		# Get suitable row from the the table.
		name = self.comboBoxName.currentText()
		sched = int(self.comboBoxSchedule.currentText())
		row = NpcPVC.selectRow(name, sched)
		length = self.lineEditLength.text()
		if row is not None:
			# Get outer and inner dimension as a number of inches.
			out_d = str(row[NPC_OUTER_DIAMETER_COLUMN_INDEX]) + " in"
			in_d = str(row[NPC_INNER_DIAMETER_COLUMN_INDEX]) + " in"
			print("Creating pipe with O.D="+out_d+", I.D="+in_d+", L="+length)
			createPipe(out_d, in_d, length, "PvcPipe")
			# Store the user's input for future use.
			self.storeInput()
		else:
			print("Dimiensions not found")

		# Call parent class.
		super(AddPvcPipeNpsGuiClass, self).accept()

	def selectComboBoxText(self, cb, text):
		if text is not None:
			index = cb.findText(text, QtCore.Qt.MatchFixedString)
			if index >= 0:
				cb.setCurrentIndex(index)
				return index
		return -1

	def restoreRecentInput(self):
		settings = QtCore.QSettings("OSE", "OSE - add pipe macro.")
		# Restore the selection of the comboBoxName.
		text = settings.value("comboBoxName")
		self.selectComboBoxText(self.comboBoxName, text)
		text = settings.value("comboBoxSchedule")
		self.selectComboBoxText(self.comboBoxSchedule, text)
		text = settings.value("lineEditLength")
		if text is not None:
			self.lineEditLength.setText(text)
		
		# Restore the selction of the comboBoxSchedule
	def storeInput(self):
		settings = QtCore.QSettings("OSE", "OSE - add pipe macro.")
		settings.setValue("comboBoxName", self.comboBoxName.currentText())
		settings.setValue("comboBoxSchedule", self.comboBoxSchedule.currentText())
		settings.setValue("lineEditLength", self.lineEditLength.text())

# Show Dialog
form = AddPvcPipeNpsGuiClass()
#form.exec_() # What is it for?





# Macro End: /home/ruslan/.FreeCAD/create-pipe.FCMacro +++++++++++++++++++++++++++++++++++++++++++++++++
