import sys # for debug print

def createSelOptionsLoop(key, value, valInputDict, inKey, commentKey, withComment):
  showComment = False
  commentText = ""
  retStr = f"<option value=\"{key}\""
  #print(f"valInputDict: {valInputDict}", file=sys.stderr)
  if valInputDict[f"{inKey}_select"] == key:
    retStr += " selected=\"selected\""
    if withComment and key == commentKey:
      showComment = True
  if withComment and key == commentKey:
    retStr += f" data-id=\"{commentKey}_p\" "
    #retStr += f" onclick=\"setVisible(\'{commentKey}_p\')\""
    commentText += f"- {value['kommentartext']}<br>"
  retStr += ">" + value['menutext'] + "</option>\n"
  return retStr, showComment, commentText


def createSelOptions(inMetaDict, valInputDict, metaValTopKey, inKey, commentKey, withComment):
    commentText = ""
    showComment = False
    retStr = ""
    if metaValTopKey:
      for key, value in inMetaDict[metaValTopKey][inKey]['options'].items():
        retStrTmp, showCommentTmp, commentTextTmp = createSelOptionsLoop(key, value, valInputDict, inKey, commentKey, withComment)
        retStr += retStrTmp
        commentText += commentTextTmp
        if showCommentTmp:
          showComment = True
    else:
      for key, value in inMetaDict[inKey]['options'].items():
        retStrTmp, showCommentTmp, commentTextTmp = createSelOptionsLoop(key, value, valInputDict, inKey, commentKey, withComment)
        retStr += retStrTmp
        commentText += commentTextTmp
        if showCommentTmp:
          showComment = True
    return retStr, commentText, showComment

def createPureSelect(inMetaDict, metaValTopKey, anwTyp, valInputDict, inKey, commentKey = ''):
    withComment = False
    if commentKey:
      withComment = True
    retStr = f"<select id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['selColNames'][0]}\" "
    if withComment:
      retStr += f"onchange=\"setVisible(this.options[this.selectedIndex].dataset.id)\" "
    retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['selColNames'][0]}\" class=\"form-control\">"
    optionsStr, commentText, showComment = createSelOptions(inMetaDict, valInputDict, metaValTopKey, inKey, commentKey, withComment)
    retStr += optionsStr
    retStr += '</select>'
    if withComment and showComment:
      retStr += f"""
        <p id="{commentKey}_p" class="small-text" style="display: inline;">{commentText}</p>
      """
    elif withComment:
      retStr += f"""
        <p id="{commentKey}_p" class="small-text" style="display: none;">{commentText}</p>
      """
    return retStr

def createSelectTabRowWithTransport(inMetaDict, metaValTopKey, anwTyp, valInputDict, inKey, commentKey = ''):
    withComment = False
    if commentKey:
      withComment = True
    retStr = "<tr><td>"
    selKey = f"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['selColNames'][0]}"
    retStr += f"<label class=\"{inKey}_label\" for=\"{selKey}\">{inMetaDict[metaValTopKey][inKey]['label']['text']}</label><br>"
    retStr += "</td><td>"
    retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
    retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
    valKey = f"{inKey}_masse"
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"kg/m³\" value=\"{valInputDict[valKey]}\">"
    retStr += "</td><td>"
    retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
    retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
    valKey = f"{inKey}_lkw"
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[valKey]}\">"
    retStr += "</td><td>"
    retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
    retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
    valKey = f"{inKey}_bahn"
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[valKey]}\">"
    retStr += "</td></tr>"
    retStr += "<tr><td colspan='4'>"
    retStr += f"<select id=\"{selKey}\" "
    retStr += f"name=\"{selKey}\" class=\"form-control\">"
    optionsStr, commentText, showComment = createSelOptions(inMetaDict, valInputDict, metaValTopKey, inKey, commentKey, withComment)
    retStr += optionsStr
    retStr += "</select>"
    retStr += "</td></tr>"
    retStr += "<tr><td colspan='4'>"
    retStr += f"<p id=\"{commentKey}_p\" class=\"small-text\" "
    if showComment:
      retStr += f"style=\"display: inline\">"
    else:
      retStr += f"style=\"display: none\">"
    retStr += f"{commentText}</p>"
    retStr += "</td></tr>"
    return retStr

def createSelectTabRowWithTransportHidden(inMetaDict, metaValTopKey, anwTyp, valInputDict, inKey, commentKey = ''):
    hiddenVal = f"{inKey}_masse"
    #print(f"{hiddenVal}: {valInputDict[hiddenVal]}", file=sys.stderr)
    if float(valInputDict[hiddenVal]) == 0.0:  # hier verdopple ich die Funktion  createSelectTabRowWithTransport nur wegen dem class tag
      withComment = False
      if commentKey:
        withComment = True
      retStr = "<tr class=\"noPrint\"><td>"
      selKey = f"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['selColNames'][0]}"
      retStr += f"<label class=\"{inKey}_label\" for=\"{selKey}\">{inMetaDict[metaValTopKey][inKey]['label']['text']}</label><br>"
      retStr += "</td><td>"
      retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
      retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
      valKey = f"{inKey}_masse"
      retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"kg/m³\" value=\"{valInputDict[valKey]}\">"
      retStr += "</td><td>"
      retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
      retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
      valKey = f"{inKey}_lkw"
      retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[valKey]}\">"
      retStr += "</td><td>"
      retStr += f"<input id=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
      retStr += f"name=\"{inKey}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
      valKey = f"{inKey}_bahn"
      retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[valKey]}\">"
      retStr += "</td></tr>"
      retStr += "<tr class=\"noPrint\"><td colspan='4'>"
      retStr += f"<select id=\"{selKey}\" "
      retStr += f"name=\"{selKey}\" class=\"form-control\">"
      optionsStr, commentText, showComment = createSelOptions(inMetaDict, valInputDict, metaValTopKey, inKey, commentKey, withComment)
      retStr += optionsStr
      retStr += "</select>"
      retStr += "</td></tr>"
      retStr += "<tr><td colspan='4'>"
      retStr += f"<p id=\"{commentKey}_p\" class=\"small-text\" "
      if showComment:
        retStr += f"style=\"display: inline\">"
      else:
        retStr += f"style=\"display: none\">"
      retStr += f"{commentText}</p>"
      retStr += "</td></tr>"
    else:
      retStr = createSelectTabRowWithTransport(inMetaDict, metaValTopKey, anwTyp, valInputDict, inKey, commentKey)
    return retStr

def createValueTabRowWithTransport(inMetaDict, metaValTopKey, anwTyp, valInputDict, key):
    retStr = "<tr><td>"
    retStr += f"<label class=\"{key}_label\" for=\"{key}\">{inMetaDict[metaValTopKey][key]['label']['text']}</label>"
    retStr += "</td><td>"
    try:
      retStr += f"<input id=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
      retStr += f"name=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
      inKey = f"{key}_masse"
      retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"kg/m³\" value=\"{valInputDict[inKey]}\">"
    except:
      import traceback
      retStr += f"<pre>Python error:\n{traceback.format_exc()}<br>{valInputDict}</pre>"
    retStr += "</td><td>"
    retStr += f"<input id=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
    retStr += f"name=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][1]}\" "
    inKey = f"{key}_lkw"
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[inKey]}\">"
    retStr += "</td><td>"
    retStr += f"<input id=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
    retStr += f"name=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][2]}\" "
    inKey = f"{key}_bahn"
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"km\" value=\"{valInputDict[inKey]}\">"
    retStr += "</td></tr>"
    return retStr

def createPureValueInput(inMetaDict, metaValTopKey, anwTyp, valInputDict, key):
    retStr = f"<label class=\"{key}_label\" for=\"{key}\">{inMetaDict[metaValTopKey][key]['label']['text']}</label>"
    retStr += f"<input id=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
    retStr += f"name=\"{key}_{inMetaDict['rechnertyp']['options'][anwTyp]['valColNames'][0]}\" "
    inKey = f"{key}_masse"
    retValue = valInputDict[inKey]
    if retValue == '0' or retValue == 0:
      retValue = ''
    retStr += f"type=\"text\" class=\"form-control col-text-right\" placeholder=\"kg/m³\" value=\"{retValue}\">"
    return retStr

def createHiddenInput(metaDict, metaKey, inDict):
  formKey = f"{metaKey}_select"
  try:
    return f"<input type=\"hidden\" id=\"{formKey}_hidden\" name=\"{formKey}\" value=\"{inDict[formKey]}\">"
  except Exception as e:
    print(e, file=sys.stderr)
    print(f"{inDict}", file=sys.stderr)

def showSelectComment(selectDict, inData, inKey, commentKey):
    retStr = "none"
    for key, value in selectDict.items():
        if inData[f"{inKey}_select"] == key:
            if key == commentKey:
                retStr = "inline"
    return retStr

def createValue(val):
  if isinstance(val, int):
    return str(val)
  else:
    if len(val)>0 and val != '0':
        return val;
    else:
        return ""

def createShortInputForm(input_meta, input_data, inputErrors, anwTyp):
  retStr = f"""
          {createHiddenInput(input_meta, 'rechnertyp', input_data)}
          {createHiddenInput(input_meta, 'actTabInput', input_data)}
          {createHiddenInput(input_meta, 'umwindikator', input_data)}
          <h1 class=\"sidebartitle\">Betondefinition für Planer:innen</h1>
          <div class=\"form-group\">
            <input type=\"submit\" name=\"calc_result\" value=\"Resultat berechnen\">
          """
  if inputErrors == "":
    retStr += f"""<input type="submit"  name=\"change2detail\" value="Zu detaillierter Erfassung wechseln">"""
  retStr += f"""
          </div>
          <p style=\"color: red;\">{inputErrors}</p>
          <div class=\"form-group\">
            <label class=\"control-label\" for=\"anwendung\">Betonanwendung</label>
            <div>
              {createPureSelect(input_meta, '', anwTyp, input_data, 'anwendung')}
            </div>
          </div>
          <div class=\"form-group\">
            <label class=\"control-label\" for=\"sorte\">Betonsorte</label>
            <div>
              {createPureSelect(input_meta, '',  anwTyp, input_data, 'sorte')}
            </div>
          </div>
          <div class=\"form-group\">
            <label class=\"control-label\" for=\"cemtyp\">Zementtyp</label>
            <div>
              {createPureSelect(input_meta, 'bestandteile',  anwTyp, input_data, 'cemtyp', 'cemHUKRHofmannGreen')}
            </div>
          </div>
          <h1 class=\"sidebartitle\">Einspeicherung CO₂</h1>
          <p>Ob und wie dieser eingelagerte Kohlenstoff als Negativemission anrechenbar ist, wird in Label- und Nachweissystemen auf Gebäudeebene geregelt.<br>Die unten angegebene Menge zugegebener Pflanzenkohle oder eingespeichertes CO₂ wird verwendet, um den Herstellungsaufwand in der Ökobilanz einzurechnen.</p>
          <p>Pro m³ <strong>un</strong>bewehrtem Beton</p>
          <div class=\"form-group\">
            {createPureValueInput(input_meta, 'bestandteile', anwTyp, input_data, 'einspeicherungKohle')}
          </div>
          <div class=\"form-group\">
            {createPureValueInput(input_meta, 'bestandteile', anwTyp, input_data, 'einspeicherungGranulat')}
          </div>
          <h1 class=\"sidebartitle\">Bewehrung</h1>
          <p>Pro m³ bewehrtem Beton</p>
          <div class=\"form-group\">
            {createPureValueInput(input_meta, 'bestandteile', anwTyp, input_data, 'bewehrung')}
            {createPureSelect(input_meta, 'bestandteile',  anwTyp, input_data, 'bewehrung')}
          </div>
          <p style=\"color: red;\">{inputErrors}</p>
          <input type=\"submit\" name=\"calc_result\" value=\"Resultat berechnen\">
  """
  return retStr

def createDetailedInputForm(input_meta, input_data, inputErrors, anwTyp):
  retStr =  f"""
          {createHiddenInput(input_meta, 'rechnertyp', input_data)}
          {createHiddenInput(input_meta, 'actTabInput', input_data)}
          {createHiddenInput(input_meta, 'umwindikator', input_data)}
          <h1 class=\"sidebartitle\">Betondefinition für Hersteller:innen</h1>
          <div class=\"form-group\">
          <input type=\"submit\" value=\"Resultat berechnen\">
          """
  if inputErrors == "":
    retStr +=  f"""<input type="submit"  name=\"change2npk\" value="Zu NPK-/vereinfachter Erfassung wechseln">"""
  retStr +=  f"""
          </div>
          <p style=\"color: red;\">{inputErrors}</p>
          <div class=\"form-group\">
            <label class=\"control-label\" for=\"anwendung\">Betonanwendung</label>
            <div>
              {createPureSelect(input_meta, '', anwTyp, input_data, 'anwendung')}
            </div>
          </div>
          <h1 class=\"sidebartitle\">Zusammensetzung</h1>
          <div class=\"form-group\">
            <table class="printPageBreak">
              <colgroup>
                <col class="col-wide-4cols">
                <col class="col-normal-4cols">
                <col class="col-short-4cols">
                <col class="col-short-4cols">
                </colgroup>
              <thead>
              <th class=\"control-label\">Zusammensetzung für 1m³ unbewehrten Beton</th>
              <th class=\"control-label\">Masse [<span style=\"white-space: nowrap;\">kg/m³</span>]</th>
              <th class=\"control-label\">Transport-Distanz LKW [km]</th>
              <th class=\"control-label\">Transport-Distanz Bahn [km]</th>
            </thead>
            <tbody>
              {createSelectTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'cemtyp','cemHUKRHofmannGreen')}
              {createSelectTabRowWithTransportHidden(input_meta, 'bestandteile', anwTyp, input_data, 'cemtyp2','cemHUKRHofmannGreen')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'betongranulat')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'mischgranulat')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'kies_rund')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'kies_gebrochen')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'sand')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'kalksteinmehl')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'flugasche')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'fliessmittel')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'weitere_zusaetze')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'wasser')}
           </tbody></table>
            <h1 class=\"sidebartitle\">Einspeicherung CO₂</h1>
            <p>Ob und wie dieser eingelagerte Kohlenstoff als Negativemission anrechenbar ist, wird in Label- und Nachweissystemen auf Gebäudeebene geregelt.<br>Die unten angegebene Menge zugegebener Pflanzenkohle oder eingespeichertes CO₂ wird verwendet, um den Herstellungsaufwand in der Ökobilanz einzurechnen.</p>
            <table>
              <colgroup>
                <col class="col-wide-4cols">
                <col class="col-normal-4cols">
                <col class="col-short-4cols">
                <col class="col-short-4cols">
              </colgroup>
              <thead>
              <th class=\"control-label\">Pro m³ <strong>un</strong>bewehrtem Beton</th>
              <th class=\"control-label\">Masse [<span style=\"white-space: nowrap;\">kg/m³</span>]</th>
              <th class=\"control-label\">Transport-Distanz LKW [km]</th>
              <th class=\"control-label\">Transport-Distanz Bahn [km]</th>
            </thead>
            <tbody>
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'einspeicherungKohle')}
              {createValueTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'einspeicherungGranulat')}
            </tbody></table>
            <p class="noPrint">Hinweis, falls Granulat mit fixiertem CO₂ verwendet wird: In der Zusammensetzung bitte die Masse Recyclinggranulat ohne fixiertes CO₂ eingeben.</p>
            <h1 class=\"sidebartitle\">Bewehrung</h1>
            <table>
              <colgroup>
                <col class="col-wide-4cols">
                <col class="col-normal-4cols">
                <col class="col-short-4cols">
                <col class="col-short-4cols">
              </colgroup>
              <thead>
              <th class=\"control-label\">Pro m³ bewehrtem Beton</th>
              <th class=\"control-label\">Masse [<span style=\"white-space: nowrap;\">kg/m³</span>]</th>
              <th class=\"control-label\">Transport-Distanz LKW [km]</th>
              <th class=\"control-label\">Transport-Distanz Bahn [km]</th>
            </thead><tbody>
              {createSelectTabRowWithTransport(input_meta, 'bestandteile', anwTyp, input_data, 'bewehrung')}
            </tbody></table>
          </div>
          <p style=\"color: red;\">{inputErrors}</p>
          <input type=\"submit\" name=\"calc_result\" value=\"Resultat berechnen\">
  """
  return retStr

def createInputForm(input_meta, input_data, inputErrors, anwTyp):
  if anwTyp == 'npkDefinition':
    return createShortInputForm(input_meta, input_data, inputErrors, anwTyp)
  elif anwTyp == 'detailedDefinition':
    return createDetailedInputForm(input_meta, input_data, inputErrors, anwTyp)

def createUserInfo(anwTyp):
  retText = ''''''
  if anwTyp == 'npkDefinition':
    retText += '''<p class="noPrint">Mit dem Betonsortenrechner können Sie die Umweltwirkungen pro m³ Beton für unterschiedliche Anwendungsbereiche, Betonsorten und eingesetzten Zementtypen berechnen.</p>
    <p>Klicken Sie auf den Knopf «Zu detaillierter Erfassung wechseln», um zum Rechner für Hersteller zu gelangen.'''
  elif anwTyp == 'detailedDefinition':
    retText += '''<p class="noPrint">Mit dem Betonsortenrechner können Sie die Umweltwirkungen pro m³ Beton Ihrer werkspezifischen Betonsorten zusammenstellen und berechnen. Geben Sie die Zusammensetzung für einen m³ Beton ohne Bewehrung ein. Falls Sie gewisse Transportdistanzen nicht kennen, können Sie die Standardvorgabe des Rechners verwenden.</p>
    <p class="noPrint">Wenn sie eine Bewehrung angeben, wird das Resultat pro m³ bewehrtem Beton ausgegeben und das Betonvolumen entsprechend reduziert.</p>'''
  retText += '''<p class="noPrint">Die «Ökobilanz-Resultate» sind in drei Reiter aufgeteilt. Unter «Übersicht-Resultate» werden alle Umweltindikatoren für Herstellung und Entsorgung ausgewiesen. Unter «Details Resultate» können Sie den gewünschten Umweltindikator auswählen. Die Resultate werden in dieser Ansicht aufgeschlüsselt nach der Herstellung des Zements, der Gesteinskörnung, der restlichen Herstellung und der Bewehrung. Unter dem Reiter «Zusammensetzung Beton» wird die Zusammensetzung ausgewiesen, die für die Berechnung verwendet wurde.</p>
  <p>Welche Betonsorten in der Schweiz gemäss Norm SN EN 206+A2:2021 freigegeben sind, entnehmen Sie bitte dem SIA Register der frei gegebenen Zemente und Kombinationen von Zementen und Zusatzstoffen.</p>
  <p>Der Ökobilanzrechner für Betonsorten, seine Bedienung und Funktion werden im "Hintergrundbericht Ökobilanzrechner für Betonsorten" beschrieben.</p>
  <p>Die dem Rechner zugrunde liegenden Ökobilanzen wurden mit dem UVEK Ökobilanzdatenbestand 2022 plus Aktualisierungen herstellerspezifischer Daten berechnet.</p>
  <p>Weitere Informationen:</p>
  <p><a href="../doc/Hintergrundbericht_Oekobilanzrechner_Betonsorten_v4.pdf" target="_blank">Hintergrundbericht zum Betonsortenrechner</a></p><p>
  <a href="https://www.sia.ch/register" target="_blank">SIA 262 - Register der freigegebenen Zemente und Kombinationen von Zementen und Zusatzstoffen</a></p>
  '''
  return retText


