# -*- coding: utf-8 -*-

# Copyright 2011-2014, extragroup GmbH, Pottkamp 19, 48149 Münster, Germany
# All rights reserved
#
# All information contained herein is, and remains the property of
# extragroup GmbH and its suppliers, if any. The intellectual and
# technical concepts contained herein are proprietary to extragroup GmbH
# and its suppliers and are protected by trade secret or copyright law.
# Dissemination of this information or reproduction of this material is
# strictly forbidden unless prior written permission is obtained from
# extragroup GmbH

from interiorcad.cuttinglistexport.csvbase import CuttinglistExportCSVBase
import interiorcad.backend.exportsettingsfile
import interiorcad.interface.configurationkeys as ConfigurationKeys


class AK_Soft(CuttinglistExportCSVBase):
	def __init__(self, **keywords):
		super().__init__(**keywords)
		self.exportsettingsfile = interiorcad.backend.exportsettingsfile.ExportSettingsFile()
		self.csvdelimiter = ';'
		self.EXTENSION = 'csv'
		self.EXPORT_LOCATION = self.getCuttinglistConfiguration().get('export-location', 'file')  # | clipboard
		self.SCOPE_OF_EXPORT = self.getCuttinglistConfiguration().get('scope-of-export', 'partsonly')  # | partsandfittings | fittingsonly
		self.CUMULATE_FITTINGS = self.getCuttinglistConfiguration().getAsBool('cumulate-fittings', True)
		self.EXPORT_FORMAT = 'AK Soft'
		self.KantenReihenfolge = self.getCuttinglistConfiguration().get('AKSoft-Kantenreihenfolge', '2')
		self.KantenIDKante = self.getCuttinglistConfiguration().get('KantenID Kante', '')
		self.KantenIDKeineKante = self.getCuttinglistConfiguration().get('KantenID keine Kante', '')
		self.MoePosNrn = [] #Liste mit Positionsnummern
		self.MoePosBezn = [] #Liste mit Positionsnamen
		self.Moebelnamen = [] #Liste mit Moebelnamen
		self.PosIDs = [] #Liste mit PosNr+Moebelname
		self.counter = 0
		self.export_process = '_'



	def doCuttinglistExport(self, **keywords):
		if self.EXPORT_LOCATION == 'clipboard':
			self.doClipboardExport(**keywords)
		elif self.EXPORT_LOCATION == 'fileandclipboard':
			self.doFileExport(**keywords)
			self.doClipboardExport(**keywords)
		else:
			self.doFileExport(**keywords)

	def getHeaderLine(self, **keywords):
		return ('DokumentName',
				'ProjektNr',
				'Kommission',
				'PositionNr',
				'PosBezeichnung',
				'PosNrExport',
				'PosBezExport',
				'Moebelname',
				'TeileNummer',
				'Teilebezeichnung',
				'TeileID',
				'Traegermaterial',
				'Anzahl',
				'FertigLaenge', 'FertigBreite', 'FertigDicke',
				'ZuschnittLaenge', 'ZuschnittBreite', 'ZuschnittDicke',
				'ZuschnittStrategie',
				'Zugabe',
				'Fuegen',
				#'FuegenMinMax',
				'Ka1C','Ka1C_Art', 'Ka1C_Di','Ka1C_FK','Ka1C_ID',
				'Ka4D','Ka4D_Art', 'Ka4D_Di','Ka4D_FK','Ka4D_ID',
				'Ka2E','Ka2E_Art', 'Ka2E_Di','Ka2E_FK','Ka2E_ID',
				'Ka3F','Ka3F_Art', 'Ka3F_Di','Ka3F_FK','Ka3F_ID',

				'BA','Be_A_Mat','BA_Di','BI', 'Be_I_Mat','BI_Di',
				'OA','OA_Mat','OI', 'OI_Mat',
				'NC_I', 'NC_A',
				'Bemerkung',
				'Export Notiz',)

	def MoePosNrGenerieren(self, MoePosNr, MoePosBez, Moebelname, PosID):
		if MoePosNr == None or MoePosNr == '':  # keine Position zugewiesen #--> Möbelname wird verwendet
			MoePosNr = '99'
			MoePosBez = 'keine Pos'
			self.export_process = self.export_process+'_Pos nicht zugewiesen'
		if  not MoePosNr.isdigit():
			MoePosNr = '99'
			MoePosBez = 'keine Pos'
			self.export_process = self.export_process+'_Pos keine integer'
		self.counter += 1
		return MoePosNr, MoePosBez

	def TranslateStragety(self, s):
		StratDict={'nc-compatible':'Gemäss NC-Ausgabe','sawn-size':'Rohmass','sawn-size-with-addition':'Rohmass + Zugabe','finished-size':'Fertigmass','finished-size-with-addition':'Fertigmass+Zugabe'}
		return StratDict.get(s)

	def TranslateKanten(self, n, s):
		StratDict={'':'00','Continuous':'10','Discontinuous':'20','Miter':'30'}
		#self.export_process = self.export_process+' '+s+' Ka'+str(n)+' ___'
		if self.KantenReihenfolge == '2': #längs durchlaufend
			if n == 1 or n == 2: # längskanten
				self.export_process = self.export_process+'_102'
				StratDict={'':'00','Continuous':'10','Discontinuous':'10','Miter':'10'}
			else:
				self.export_process = self.export_process+'_105'
				StratDict={'':'00','Continuous':'20','Discontinuous':'20','Miter':'20'}
		if self.KantenReihenfolge == '1': #Breite durchlaufend
			if n == 3 or n == 4: # längskanten
				StratDict={'':'00','Continous':'20','Discontinuous':'20','Miter':'20'}
		return StratDict.get(s)

	def SplitKa(self, Artikel):
		code = ''
		kante = Artikel
		if '$' in Artikel:
			kante, code = Artikel.split('$')

		return kante, code

	def gibtEs(self,input):
		output = 2
		if input != '':
			output = 1
		return output

	def generate_KaID(self,Ka):
		kante, KaCode = self.SplitKa(Ka)
		if KaCode == '':
			if self.KaCode_comment == '':
				if kante != '':
					KaCode = self.KantenIDKante
				else:
					KaCode = self.KantenIDKeineKante
			else:
				KaCode = self.KaCode_comment
		return kante, KaCode

	def getElements(self, **keywords):
		self.export_process = '_'
		entry = keywords['entry']
		projectInfo = keywords['projectInfo']
		positionInfo = keywords['positionInfo']

		Moebelname = self.asString(data=positionInfo["CabinetName"], **keywords)
		MoePosBeschreibung = self.asString(data=positionInfo["PositionDescription"] , **keywords)
		MoePosNr = self.asString(data=positionInfo["PositionNumber"], **keywords)
		PosID = MoePosNr+Moebelname

		MoePosNr, MoePosBez = self.MoePosNrGenerieren(MoePosNr, MoePosBeschreibung, Moebelname, PosID)


		self.KaCode_comment = self.asString(key='part_comment', **keywords)
		Ka1 = self.asString(key='part_edge1', **keywords)
		Ka2 = self.asString(key='part_edge2', **keywords)
		Ka3 = self.asString(key='part_edge3', **keywords)
		Ka4 = self.asString(key='part_edge4', **keywords)

		kante1, KaCode1 = self.generate_KaID(Ka1)
		kante2, KaCode2 = self.generate_KaID(Ka2)
		kante3, KaCode3 = self.generate_KaID(Ka3)
		kante4, KaCode4 = self.generate_KaID(Ka4)


		#elif self.AKSoftGruppe == '2':     #interiorcad Positionsnummer
		#	MoePosBez = MoePosNr

		#elif self.AKSoftGruppe == '3':     #interiorcad Positionsname
		#	pass
		#if self.AKSoftPosition == '1':     #Position = fortlaufende Nummern in AKSoft
		#	Nummer = self.counter

		#self.asCoordinate(data=entry.workpiece.finishedSizeBounds.getLength(),**keywords),
		#self.exportsettingsfile.getSimpleValueAsBool(ConfigurationKeys.COMMON_JOINTING, False) #fügen
		#entries = self.generateSortedWorkpieceAndFittingEntries(keywords)
		#test = entry.workpiece.finishedSizeBounds
		# entry.workpiece.finishedSizeShape
		# entry,workpiece.sawnSizeBounds
		# entry.workpiece.sawnSizeShape.
		# entry.workpiece.jointingSizeBounds (nur wenn Fügemaß vorhanden ist)
		# entry.workpiece.jointingSizeShape (nur wenn Fügemaß vorhanden ist)
		#test = entry.workpiece['finishedSizeBounds']
		#test = self.asString(data=entry.finishedSizeBounds, **keywords) #geht
		#ProdStrategie = self.configuration.sizing #gem. NC mit/ohne Format = 9, Fertigmass = 0,Rohmass = 6,
		sizingText = self.exportsettingsfile.getSimpleValueAsString(ConfigurationKeys.CUTTING_OUTPUT_SIZING, 'nc-compatible')



		return (
			self.asString(data=positionInfo["DocumentName"], **keywords),
			self.asString(data=projectInfo["ProjectID"], **keywords), 				#Auftrag nicht verwendet beim Import
			keywords['positionInfo']['ProjectCommission'],
			self.asString(data=positionInfo["PositionNumber"], **keywords), 		#Native Positionsnummer
			self.asString(data=positionInfo["PositionDescription"] , **keywords),	#Native Positions-Beschreibung
			MoePosNr,																#Export Posisions Nr
			MoePosBez, 	                                              				#Export Posisions Bezeichnung
			self.asString(data=positionInfo["CabinetName"], **keywords),

			self.counter,																	#Export fortlaufende Teile Nummer
			self.asString(key='part_description', **keywords), 			#Bauteilbezeichnung
			self.asString(key='unit_unitid', **keywords), 				#Bauteilbezeichnung
			self.asString(key='part_itemid', **keywords), 				#Artikelnummer (Material)
			self.asInt(data=entry.count, **keywords),					#Anzahl immer 1
			self.asCoordinate(data=entry.workpiece.finishedSizeBounds.getLength(),**keywords),
			self.asCoordinate(data=entry.workpiece.finishedSizeBounds.getWidth(),**keywords),
			self.asCoordinate(data=entry.thickness, **keywords),
			self.asCoordinate(data=entry.boardLength, **keywords), 		#Format gemäss Exporteinstellung, Länge (AKSoft Kantenbild Senkrechte)
			self.asCoordinate(data=entry.boardWidth, **keywords), 		#Format gemäss Exporteinstellung Breite (AKSoft Kantenbild Horizontal)
			self.asCoordinate(data=entry.boardThickness, **keywords), 	#Wird zusammen mit Artikel in AKSoft als Importartikel eingelesen
			self.TranslateStragety(sizingText),
			self.configuration.sizingAddition*2,
			self.exportsettingsfile.getSimpleValueAsBool(ConfigurationKeys.COMMON_JOINTING, False),
			#str(self.exportsettingsfile.getSimpleValueAsBool(ConfigurationKeys.COMMON_JOINTING_MIN, False))+' '+
			#str(self.exportsettingsfile.getSimpleValueAsBool(ConfigurationKeys.COMMON_JOINTING_MAX, False)),

			#Kante C VW Kante 1
			self.gibtEs(Ka1),
			kante1,
			self.asCoordinate(key='part_edge1thickness', **keywords),
			self.TranslateKanten(4, self.asString(key='part_edge4endjoint', **keywords)),
			KaCode1,

			#Kante D VW Kante 4
			self.gibtEs(Ka4),
			kante4,
			self.asCoordinate(key='part_edge4thickness', **keywords),
			self.TranslateKanten(2, self.asString(key='part_edge2endjoint', **keywords)),
			KaCode4,

			#Kante E VW Kante 2
			self.gibtEs(Ka2),
			kante2,
			self.asCoordinate(key='part_edge2thickness', **keywords),
			self.TranslateKanten(3, self.asString(key='part_edge3endjoint', **keywords)),
			KaCode2,

			#Kante F VW Kante 3
			self.gibtEs(Ka3),
			kante3,
			self.asCoordinate(key='part_edge3thickness', **keywords),
			self.TranslateKanten(1, self.asString(key='part_edge1endjoint', **keywords)),
			KaCode3,

			self.gibtEs(self.asString(key='part_covering2', **keywords)),
			self.asString(key='part_covering2', **keywords),
			self.asCoordinate(key='part_covering2thickness', **keywords),

			self.gibtEs(self.asString(key='part_covering1', **keywords)),
			self.asString(key='part_covering1', **keywords),
			self.asCoordinate(key='part_covering1thickness', **keywords),


			self.gibtEs(self.asString(key='part_laminate2', **keywords)),
			self.asString(key='part_laminate2', **keywords),#Beschichtung

			self.gibtEs(self.asString(key='part_laminate2', **keywords)),
			self.asString(key='part_laminate1', **keywords),#Beschichtung


			self.asString(data=entry.ncProgramNameOpposite, **keywords),#Dateipfad CNC Nebenseite
			self.asString(data=entry.ncPropramNameMain, **keywords),#Dateipfad CNC Hauptseite
			self.asString(key='part_comment', **keywords),

			self.export_process	#Error log Export
				)

	def doClipboardExport(self, **keywords):
		# Excel needs tabulators when pasting from clipboard (LibreOfficeCalc does not care, as it always shows the import dialog)
		self.csvdelimiter = '\t'
		super().doClipboardExport(**keywords)


export = AK_Soft()
export.doCuttinglistExport()
export.openExportPath()
