# Copyright (c) 2025 Martin Kayser (tebarius)
# Licensed under the MIT License. See LICENSE file in the project root.
import streamlit as st
import base64
import tools
import matplotlib.pyplot as plt
import helper

standard_output = ('#### Um den HILFE-Text zu einzelnen Funktionen aufzurufen bitte die Funktion mit leerem'
                  ' Eingabefeld aufrufen.\n'
                   '__Diese APP ist OpenSource:__  \n'
                   '- Sourcecode: https://gitea.tebarius.duckdns.org/tebarius/Mysteryhelfer-web\n'
                   '- Docker-Images sind verfügbar via:\n'
                   '  - https://hub.docker.com/r/tebarius/mysteryhelfer\n'
                   '  - https://gitea.tebarius.duckdns.org/tebarius/-/packages/container/mysteryhelfer/latest')

st.set_page_config(
    # we do also patching static-files of streamlit in the docker-container so bookmarks will have
    # the same favicon and if posting links for example in WhatsApp they will have the same title
    page_title="tebarius Mysteryhelfer (web)",
    page_icon="images/favicon.ico",
    layout="wide",
    menu_items={
        'About': '### tebarius Mysteryhelfer (web)\n'
                 'Dies ist die Umsetzung der [Desktop-App Mysteryhelfer](https://mysteryhelfer.tebarius.duckdns.org/) '
                 '([Source](https://gitea.tebarius.duckdns.org/tebarius/Mysteryhelfer)) als Web-App.  \n  \n'
                 'Für die Umsetzung kommt das Python-Framework [Streamlit](https://streamlit.io/) zum Einsatz.  \n  \n'
                 '_Der Sourcecode und Docker-Images zum selbst hosten sind auf_ '
                 '_https://gitea.tebarius.duckdns.org/tebarius/Mysteryhelfer-web verfügbar._  \n  \n'
                 'Anregungen, Hinweise, Fehlerreports gerne an: '
                 '[tba@gmx.li](mailto:tba@gmx.li?subject=Mysteryhelfer-web) oder über einen Logeintrag beim '
                 '[App-TB](https://www.geocaching.com/track/details.aspx?tracker=arx57k) '
                 '(trackbar auf geocaching.com).',
    }
)

st.logo('images/logo.png', size='large', link='https://gitea.tebarius.duckdns.org/tebarius/Mysteryhelfer-web')

logo_col, title_col = st.columns([1,4])
with logo_col:
    st.markdown(f'<a href="https://www.geocaching.com/track/details.aspx?tracker=arx57k">'
                f'<img src="data:image/png;base64,'
                f'{base64.b64encode(open("images/logo-mit-tb.png", "rb").read()).decode()}" '
                f'width="150" style="border-radius: 10px;">'
                f'</a>',
                unsafe_allow_html=True)
with title_col:
    st.write('### tebarius Mysteryhelfer (web)')

# Callback-Funktion zur Verarbeitung der Auswahl
def auswahl_verarbeiten():
    text = st.session_state.input_text
    auswahl = st.session_state.option
    st.session_state.map_data = None
    st.session_state.graph_data = None
    if auswahl == "Wähle eine Funktion":
        st.session_state.output_text = standard_output
    elif "Cesarchiffre (all)" in auswahl:
        st.session_state.output_text = tools.cesar_all(text)
    elif "BW,BWW,... ermitteln" in auswahl:
        st.session_state.output_text = tools.buchstabenwortwert(text)
    elif "Buchstabenwert -> Text" in auswahl:
        st.session_state.output_text = tools.buchstabenwert_zu_text(text)
    elif "Zeichenzählen" in auswahl:
        st.session_state.output_text = tools.zeichenanzahl(text)
    elif "Text rückwärts" in auswahl:
        st.session_state.output_text = tools.zeichenkette_reverse(text)
    elif "Quersumme(n)" in auswahl:
        st.session_state.output_text = tools.quersummen(text)
    elif "Einschlüsse zählen" in auswahl:
        st.session_state.output_text = tools.einschluss_count(text)
    elif "ABC -> Morse" in auswahl:
        st.session_state.output_text = tools.abc_to_morse(text)
    elif "Morse -> ABC" in auswahl:
        st.session_state.output_text = tools.morse_to_abc(text)
    elif "ROT5" in auswahl:
        st.session_state.output_text = tools.rot5(text)
    elif "ROT13" in auswahl:
        st.session_state.output_text = tools.rot13(text)
    elif "ROT18" in auswahl:
        st.session_state.output_text = tools.rot18(text)
    elif "ROT47" in auswahl:
        st.session_state.output_text = tools.rot47(text)
    elif "ASCII-Text -> HEX" in auswahl:
        st.session_state.output_text = tools.ascii_to_hex(text)
    elif "ASCII-Text -> DEZ" in auswahl:
        st.session_state.output_text = tools.ascii_to_dez(text)
    elif "ASCII-Text -> Octal" in auswahl:
        st.session_state.output_text = tools.ascii_to_octal(text)
    elif "ASCII-Text -> BIN (16bit)" in auswahl:
        st.session_state.output_text = tools.ascii_to_bin16(text)
    elif "ASCII-Text -> BIN (8bit)" in auswahl:
        st.session_state.output_text = tools.ascii_to_bin8(text)
    elif "HEX -> ASCII-Text" in auswahl:
        st.session_state.output_text = tools.hex_to_ascii(text)
    elif "DEZ -> ASCII-Text" in auswahl:
        st.session_state.output_text = tools.dez_to_ascii(text)
    elif "Octal -> ASCII-Text" in auswahl:
        st.session_state.output_text = tools.octal_to_ascii(text)
    elif "BIN -> ASCII-Text" in auswahl:
        st.session_state.output_text = tools.bin_to_ascii(text)
    elif "Zahlwortsuche-DE (0-12)" in auswahl:
        st.session_state.output_text = tools.zahlwortsuche_de(text)
    elif "Zahlwortsuche-EN (0-15)" in auswahl:
        st.session_state.output_text = tools.zahlwortsuche_en(text)
    elif "KENNYspeak kodieren" in auswahl:
        st.session_state.output_text = tools.kenny_kodieren(text)
    elif "KENNYspeak dekodieren" in auswahl:
        st.session_state.output_text = tools.kenny_dekodieren(text)
    elif "KENNYspeak raten" in auswahl:
        st.session_state.output_text = tools.kenny_raten(text)
    elif "Primz.Alpha dekodieren" in auswahl:
        st.session_state.output_text = tools.primzahlalphabet_dekodieren(text)
    elif "ist (n.te) Primzahl?" in auswahl:
        st.session_state.output_text = tools.primzahlpruefen(text)
    elif "zeige n.te Primzahl" in auswahl:
        st.session_state.output_text = tools.nte_primzahl(text)
    elif "Primfaktorenzerlegung" in auswahl:
        st.session_state.output_text = tools.primfaktoren(text)
    elif "HEX -> DEZ,OCT,BIN" in auswahl:
        st.session_state.output_text = tools.hex_to_dez_oct_bin(text)
    elif "DEZ -> HEX,OCT,BIN" in auswahl:
        st.session_state.output_text = tools.dez_to_hex_oct_bin(text)
    elif "OCT -> HEX,DEZ,BIN" in auswahl:
        st.session_state.output_text = tools.oct_to_hex_dez_bin(text)
    elif "BIN -> HEX,DEZ,OCT" in auswahl:
        st.session_state.output_text = tools.bin_to_hex_dez_oct(text)
    elif "Text -> Tomtom" in auswahl:
        st.session_state.output_text = tools.abc_to_tomtom(text)
    elif "Tomtom -> Text" in auswahl:
        st.session_state.output_text = tools.tomtom_to_abc(text)
    elif "Text -> Slash and Pipe" in auswahl:
        st.session_state.output_text = tools.text_to_slashpipe(text)
    elif "Slash and Pipe -> Text" in auswahl:
        st.session_state.output_text = tools.slashpipe_to_text(text)
    elif "PSE: O.zahl <-> Symbol" in auswahl:
        st.session_state.output_text = tools.periodensystem(text)
    elif "Nak-Nak -> Text" in auswahl:
        st.session_state.output_text = tools.naknak_to_text(text)
    elif "Navajo -> Text" in auswahl:
        st.session_state.output_text = tools.navajo_to_text(text)
    elif "Kreiszahl PI" in auswahl:
        st.session_state.output_text = tools.pi_suche(text)
    elif "Eulersche Zahl" in auswahl:
        st.session_state.output_text = tools.euler_suche(text)
    elif "phi (goldener Schnitt)" in auswahl:
        st.session_state.output_text = tools.goldener_schnitt_suche(text)
    elif "Anagrammsuche-DE" in auswahl:
        st.session_state.output_text = tools.anagramm_suche_de(text)
    elif "Anagrammsuche-EN" in auswahl:
        st.session_state.output_text = tools.anagramm_suche_en(text)
    elif "Wortsuche-DE" in auswahl:
        st.session_state.output_text = tools.wortsuche_de(text)
    elif "Wortsuche-EN" in auswahl:
        st.session_state.output_text = tools.wortsuche_en(text)
    elif "Re-Morse-DE" in auswahl:
        st.session_state.output_text = tools.remorse_de(text)
    elif "Re-Morse-EN" in auswahl:
        st.session_state.output_text = tools.remorse_en(text)
    elif "T9-DE dekodieren" in auswahl:
        st.session_state.output_text = tools.t9_de(text)
    elif "T9-EN dekodieren" in auswahl:
        st.session_state.output_text = tools.t9_en(text)
    elif "Vigenere-Chiffre" in auswahl:
        st.session_state.output_text = tools.vigenere(text, additional_parameter)
    elif "Wolseley-Chiffre" in auswahl:
        st.session_state.output_text = tools.wolseley(text, additional_parameter)
    elif "Mono.-Substitution" in auswahl:
        st.session_state.output_text = tools.monoalphasubstitution(text, additional_parameter)
    elif "Autokey-Chiffre" in auswahl:
        st.session_state.output_text = tools.autokey(text, additional_parameter)
    elif "Polybios kodieren" in auswahl:
        st.session_state.output_text = tools.polybios_encode(text, additional_parameter)
    elif "Polybios dekodieren" in auswahl:
        st.session_state.output_text = tools.polybios_decode(text, additional_parameter)
    elif "Klopfcode kodieren" in auswahl:
        st.session_state.output_text = tools.klopfcode_encode(text)
    elif "Klopfcode dekodieren" in auswahl:
        st.session_state.output_text = tools.klopfcode_decode(text)
    elif "Maptiles/Kachelkoord." in auswahl:
        output, mapd = tools.maptiles_kachelkoordinaten(text)
        st.session_state.output_text = output
        st.session_state.map_data = mapd
    elif "Quadtree/Quadkey" in auswahl:
        output, mapd = tools.quadtree_koordinaten(text)
        st.session_state.output_text = output
        st.session_state.map_data = mapd
    elif "Chronogramm" in auswahl:
        st.session_state.output_text = tools.chronogramm(text)
    elif "Zahl röm. <-> arabisch" in auswahl:
        st.session_state.output_text = tools.zahlen_roemisch_arabisch_umwandeln(text)
    elif "URL decode" in auswahl:
        st.session_state.output_text = tools.url_decode(text)
    elif "Reverse-Wherigo" in auswahl:
        output, mapd = tools.reversewig(text)
        st.session_state.output_text = output
        st.session_state.map_data = mapd
    elif "Base64 <-> ASCII" in auswahl:
        st.session_state.output_text = tools.base64_ascii(text)
    elif "Jägerzaun kodieren" in auswahl:
        st.session_state.output_text = tools.jaegerzaun_encrypt(text, additional_parameter)
    elif "Jägerzaun dekodieren" in auswahl:
        st.session_state.output_text = tools.jaegerzaun_decrypt(text, additional_parameter)
    elif "ADFGX kodieren" in auswahl:
        st.session_state.output_text = tools.adfgx_kodieren(text, additional_parameter)
    elif "ADFGX dekodieren" in auswahl:
        st.session_state.output_text = tools.adfgx_dekodieren(text, additional_parameter)
    elif "ADFGVX kodieren" in auswahl:
        st.session_state.output_text = tools.adfgvx_kodieren(text, additional_parameter)
    elif "ADFGVX dekodieren" in auswahl:
        st.session_state.output_text = tools.adfgvx_dekodieren(text, additional_parameter)
    elif "Brainfuck -> Text" in auswahl:
        st.session_state.output_text = tools.brainfuck_to_text(text)
    elif "Text -> Brainfuck" in auswahl:
        st.session_state.output_text = tools.text_to_brainfuck(text)
    elif "Ook -> Text" in auswahl:
        st.session_state.output_text = tools.ook_to_text(text)
    elif "Text -> Ook" in auswahl:
        st.session_state.output_text = tools.text_to_ook(text)
    elif "RLOU/RLUD -> Graph" in auswahl:
        output, graph_data = tools.rlou_to_graph(text)
        st.session_state.output_text = output
        st.session_state.graph_data = graph_data

# Standardwerte im Session State initialisieren
if 'option' not in st.session_state:
    st.session_state.option = "Wähle eine Funktion"
if 'input_text' not in st.session_state:
    st.session_state.input_text = ""
if 'output_text' not in st.session_state:
    st.session_state.output_text = standard_output
if 'map_data' not in st.session_state:
    st.session_state.map_data = None
if 'graph_data' not in st.session_state:
    st.session_state.graph_data = None

# Eingabefeld im Hauptbereich
input_text = st.text_area('Gib deinen Text hier ein und wähle eine Funktion im Menü auf der linken Seite:',
                          key='input_text',
                          height=150)

# --- Sidebar: Buttons selektieren und Aktion setzen ---
option = st.sidebar.radio("hidden_label",
                          # :color[text to be colored] -> ex.: blue[my text]
                          # supported colors:  blue, green, orange, red, violet, gray/grey, rainbow, or primary

                          # :color-badge[text in the badge] ->  ex.: blue-badge[my text]
                          # blue, green, orange, red, violet, gray/grey, or primary
                          options=("Wähle eine Funktion",
                                   ":orange[Cesarchiffre (all)]",
                                   ":orange[BW,BWW,... ermitteln]",
                                   ":blue[Buchstabenwert -> Text]",
                                   ":orange[Zeichenzählen]",
                                   ":orange[Text rückwärts]",
                                   ":blue[Quersumme(n)]",
                                   ":orange[Einschlüsse zählen]",
                                   ":green[ABC -> Morse]",
                                   ":green[Morse -> ABC]",
                                   ":green[ROT5]",
                                   ":green[ROT13]",
                                   ":green[ROT18]",
                                   ":green[ROT47]",
                                   ":orange[ASCII-Text -> HEX]",
                                   ":orange[ASCII-Text -> DEZ]",
                                   ":orange[ASCII-Text -> Octal]",
                                   ":orange[ASCII-Text -> BIN (16bit)]",
                                   ":orange[ASCII-Text -> BIN (8bit)]",
                                   ":blue[HEX -> ASCII-Text]",
                                   ":blue[DEZ -> ASCII-Text]",
                                   ":blue[Octal -> ASCII-Text]",
                                   ":orange-badge[Zahlwortsuche-DE (0-12)]",
                                   ":orange-badge[Zahlwortsuche-EN (0-15)]",
                                   ":green[KENNYspeak kodieren]",
                                   ":green[KENNYspeak dekodieren]",
                                   ":green-badge[KENNYspeak raten]",
                                   ":green[Primz.Alpha dekodieren]",
                                   ":blue[ist (n.te) Primzahl?]",
                                   ":blue[zeige n.te Primzahl]",
                                   ":blue[Primfaktorenzerlegung]",
                                   ":blue[HEX -> DEZ,OCT,BIN]",
                                   ":blue[DEZ -> HEX,OCT,BIN]",
                                   ":blue[OCT -> HEX,DEZ,BIN]",
                                   ":blue[BIN -> HEX,DEZ,OCT]",
                                   ":green[Text -> Tomtom]",
                                   ":green[Tomtom -> Text]",
                                   ":green[Text -> Slash and Pipe]",
                                   ":green[Slash and Pipe -> Text]",
                                   ":green[PSE: O.zahl <-> Symbol]",
                                   ":green[Nak-Nak -> Text]",
                                   ":green[Navajo -> Text]",
                                   ":blue[Kreiszahl PI]",
                                   ":blue[Eulersche Zahl]",
                                   ":blue[phi (goldener Schnitt)]",
                                   ":orange-badge[Anagrammsuche-DE]",
                                   ":orange-badge[Anagrammsuche-EN]",
                                   ":orange-badge[Wortsuche-DE]",
                                   ":orange-badge[Wortsuche-EN]",
                                   ":green-badge[Re-Morse-DE]",
                                   ":green-badge[Re-Morse-EN]",
                                   ":green-badge[T9-DE dekodieren]",
                                   ":green-badge[T9-EN dekodieren]",
                                   ":green[Vigenere-Chiffre]",
                                   ":green[Wolseley-Chiffre]",
                                   ":green[Mono.-Substitution]",
                                   ":green[Autokey-Chiffre]",
                                   ":green[Polybios kodieren]",
                                   ":green[Polybios dekodieren]",
                                   ":green[Klopfcode kodieren]",
                                   ":green[Klopfcode dekodieren]",
                                   ":violet[Maptiles/Kachelkoord.]",
                                   ":violet[Quadtree/Quadkey]",
                                   ":orange[Chronogramm]",
                                   ":blue[Zahl röm. <-> arabisch]",
                                   ":orange[URL decode]",
                                   ":violet[Reverse-Wherigo]",
                                   ":green[Base64 <-> ASCII]",
                                   ":green[Jägerzaun kodieren]",
                                   ":green[Jägerzaun dekodieren]",
                                   ":green[ADFGX kodieren]",
                                   ":green[ADFGX dekodieren]",
                                   ":green[ADFGVX kodieren]",
                                   ":green[ADFGVX dekodieren]",
                                   ":green-badge[Brainfuck -> Text]",
                                   ":green-badge[Text -> Brainfuck]",
                                   ":green-badge[Ook -> Text]",
                                   ":green-badge[Text -> Ook]",
                                   ":red[RLOU/RLUD -> Graph]"
                                   ),
                          key='option',
                          on_change=auswahl_verarbeiten,
                          label_visibility='collapsed'
                          )

# Optionales einzeiliges Eingabefeld nur für bestimmte Funktionen
additional_parameter = None
if ("Vigenere-Chiffre" in option or "Wolseley-Chiffre" in option or "Autokey-Chiffre" in option or
        "Polybios kodieren" in option or "Polybios dekodieren" in option):
    additional_parameter = st.text_input(
        "Schlüsselwort:",
        placeholder="Schlüsselwort hier eingeben"
    )
elif "Mono.-Substitution" in option:
    additional_parameter = st.text_input(
        "Schlüsselwort/Schlüsselalphabet:",
        placeholder="Schlüsselwort/Schlüsselalphabet hier eingeben"
    )
elif "Jägerzaun kodieren" in option or "Jägerzaun dekodieren" in option:
    additional_parameter = st.text_input(
        "Schlüsselfeld:",
        placeholder="Schlüsselzahl hier eingeben"
    )
elif ("ADFGX kodieren" in option or "ADFGX dekodieren" in option or "ADFGVX kodieren" in option or
      "ADFGVX dekodieren" in option):
    additional_parameter = st.text_input(
        "Passwörter:",
        placeholder="PasswortEins, PasswortZwei"
    )

# Button zum manuellen Ausführen der Verarbeitungsfunktion
if st.button(f"{st.session_state.option}"):
    auswahl_verarbeiten()

# Ausgabefeld
st.markdown(st.session_state.output_text)

# Karte anzeigen, falls aktiviert
if st.session_state.map_data is not None:
    st.subheader("Kartenansicht")
    helper.show_map_folium(st.session_state.map_data)


if st.session_state.graph_data is not None:
    fig, ax = plt.subplots()
    for segment in st.session_state.graph_data:
        x, y = zip(*segment)
        ax.plot(x, y, marker='')
    ax.set_aspect('equal', adjustable='box')
    ax.axis('off')
    st.pyplot(fig)
