﻿B4A=true
Group=Default Group
ModulesStructureVersion=1
Type=Class
Version=13.1
@EndOfDesignText@
#Region Class Module
'Class module for displaying code with syntax highlighting and copy functionality
Sub Class_Globals
'	Private mEventName As String 'Event name for callbacks
'	Private mCallBack As Object 'Callback module
	Private mCodeView As WebView
	Private mCode As String 'Stores the code to display
	Private mParent As Panel 'Parent view to hold CodeView
	Private mLanguage As String 'Programming language for syntax highlighting
	Private mThem As String 'Theme for syntax highlighting (e.g., "default", "dark")
End Sub

'Initializes the CodeView
'EventName: Name for events
'CallBackModule: Module to handle events
'Parent: Parent panel to add the CodeView
'Left, Top, Width, Height: Position and size
'Language: Programming language (e.g., "java", "vb", "html")
'Them: Highlight.js theme (e.g., "default", "dark")
Public Sub Initialize(EventName As String, CallBackModule As Object, Parent As Panel, Left As Int, Top As Int, Width As Int, Height As Int, Language As String, Them As String)
'	mEventName = EventName
'	mCallBack = CallBackModule
	mParent = Parent
	mLanguage = Language
	mThem = Them

	'Initialize WebView for code display
	mCodeView.Initialize("CodeView")
	mCodeView.JavaScriptEnabled=True
	mCodeView.ZoomEnabled = False 'Disable pinch-to-zoom
	mParent.AddView(mCodeView, Left, Top, Width, Height - 50dip)

	'Initialize Copy button with B4X styling
'	btnCopy.Initialize("btnCopy")
'	btnCopy.Text = "Copy"
'	btnCopy.TextSize = 14
'	btnCopy.Color = Colors.ARGB(255, 33, 150, 243) 'Material Blue
'	btnCopy.TextColor = Colors.White
'	mParent.AddView(btnCopy, Left + Width - 100dip, Top + Height - 50dip, 100dip, 40dip)
End Sub

'Sets the code to display
Public Sub SetCode(Code As String)
	If Code = "" Then
		mCode = "No code provided"
		Log("Warning: Empty code provided to CodeView")
	Else
		mCode = Code
	End If
'	Log("SetCode: Language=" & mLanguage & ", Code=" & mCode)
	Dim html As String = GenerateHtmlCode(mCode, mLanguage, mThem)
'	Log("SetCode: Generated HTML=" & html)
	mCodeView.LoadHtml(html)
End Sub

'Generates HTML with Highlight.js for syntax highlighting
Private Sub GenerateHtmlCode(Code As String, Language As String, Them As String) As String
	Dim escapedCode As String = EscapeHtml(Code)
	Dim themeCss As String
	Dim backgroundColor As String
	If Them.ToLowerCase = "dark" Then
		themeCss = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/atom-one-dark.min.css"
		backgroundColor = "#282c34"
	Else
		themeCss = "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/default.min.css"
		backgroundColor = "#ffffff"
	End If

	Return $"
    <!DOCTYPE html>
    <html>
    <head>
        <meta name='viewport' content='width=device-width, initial-scale=1'>
        <link rel='stylesheet' href='${themeCss}'>
        <script src='https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js'></script>
        <script>
            document.addEventListener('DOMContentLoaded', function() {
                hljs.highlightAll();
            });

            function copyCode() {
					    try {
					        const codeElement = document.querySelector('code');
					        const btn = document.getElementById('copyBtn');
					        if (!codeElement) throw new Error('No <code> element found');
					        if (!btn) throw new Error('No button with id="copyBtn" found');

					        const codeText = codeElement.innerText;

					        // Try modern Clipboard API
					        if (navigator.clipboard) {
					            navigator.clipboard.writeText(codeText).then(() => {
					                btn.innerText = 'Copied!';
					                btn.style.background = '#4CAF50';
					                setTimeout(() => {
					                    btn.innerText = 'Copy';
					                    btn.style.background = '#2196F3';
					                }, 1000);
					            }).catch(err => {
					                console.error('Clipboard API failed:', err);
					                // Fallback to execCommand
					                const textarea = document.createElement('textarea');
					                textarea.value = codeText;
					                document.body.appendChild(textarea);
					                textarea.select();
					                document.execCommand('copy');
					                document.body.removeChild(textarea);
					                btn.innerText = 'Copied!';
					                btn.style.background = '#4CAF50';
					                setTimeout(() => {
					                    btn.innerText = 'Copy';
					                    btn.style.background = '#2196F3';
					                }, 1000);
					            });
					        } else {
					            // Fallback for WebViews without Clipboard API
					            const textarea = document.createElement('textarea');
					            textarea.value = codeText;
					            document.body.appendChild(textarea);
					            textarea.select();
					            document.execCommand('copy');
					            document.body.removeChild(textarea);
					            btn.innerText = 'Copied!';
					            btn.style.background = '#4CAF50';
					            setTimeout(() => {
					                btn.innerText = 'Copy';
					                btn.style.background = '#2196F3';
					            }, 1000);
					        }
					    } catch (err) {
					        console.error('Error in copyCode:', err);
					    }
					}
        </script>
        <style>
            body {
                margin: 0;
                font-family: Arial, sans-serif;
                background: ${backgroundColor};
                position: relative;
            }
            pre {
                margin: 0;
                padding: 10px;
                overflow-x: auto;
            }
            code {
                font-size: 14px;
                line-height: 1.5;
            }
            #copyBtn {
                position: fixed;
                top: 10px;
                right: 10px;
                background: #2196F3;
                color: white;
                border: none;
                padding: 6px 12px;
                border-radius: 6px;
                font-size: 12px;
                cursor: pointer;
                z-index: 1000;
                box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            }
        </style>
    </head>
    <body>
        <button id='copyBtn' onclick='copyCode()'>Copy</button>
        <pre><code class='${Language}'>${escapedCode}</code></pre>
    </body>
    </html>
    "$
End Sub


Private Sub EscapeHtml(Text As String) As String
	Text = Text.Replace("&", "&amp;")
	Text = Text.Replace("<", "&lt;")
	Text = Text.Replace(">", "&gt;")
	Text = Text.Replace("""", "&quot;")
	Text = Text.Replace("'", "&#39;")
	Return Text
End Sub

'Changes the programming language for syntax highlighting
Public Sub SetLanguage(Language As String)
	mLanguage = Language
	SetCode(mCode) 'Refresh the display
End Sub

'Changes the theme (e.g., "default" or "dark")
Public Sub SetTheme(Them As String)
	mThem = Them
	SetCode(mCode) 'Refresh the display
End Sub
#End Region