Imports System.IO
Imports System.Xml.Serialization
Imports DigitalData.Modules.Config
Imports DigitalData.Modules.Logging
Imports DigitalData.Modules.Interfaces
Imports DigitalData.GUIs.MonoRepoUtils.Config

Public Class frmStart
    Private Const ZUGFERD_SERVICE = "ZUGFERD_SERVICE"

    Private Serializer As XmlSerializer
    Private Configs As New List(Of String) From {
        ZUGFERD_SERVICE
    }

    Private LogConfig As LogConfig
    Private Config As ConfigManager(Of Config)

    Private Sub frmStart_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ComboBoxEdit1.Properties.Items.Clear()
        ComboBoxEdit1.Properties.Items.AddRange(Configs)

        LogConfig = New LogConfig(LogConfig.PathType.CustomPath, Application.StartupPath, Nothing, "Digital Data", "Monorepo Utils")
        Config = New ConfigManager(Of Config)(LogConfig, Application.CommonAppDataPath)

        txxTemplate.Text = Config.Config.EmailTemplate.BaseHtml
        txtBannerUrl.Text = Config.Config.EmailTemplate.BannerUrl
        txtTrackingUrl.Text = Config.Config.EmailTemplate.TrackingLink
        txtOutputPath.Text = Config.Config.EmailTemplate.OutputPath
        txtADGroup.Text = Config.Config.EmailTemplate.ActiveDirectoryGroup
        txtADRoot.Text = Config.Config.EmailTemplate.ActiveDirectoryRoot
    End Sub

    Private Sub SimpleButton1_Click(sender As Object, e As EventArgs) Handles SimpleButton1.Click
        Dim oConfigName = ComboBoxEdit1.SelectedItem

        Select Case oConfigName
            Case ZUGFERD_SERVICE
                MemoEdit1.Text = CreateConfigTemplate(Of DDZUGFeRDService.Config)()

            Case Else
                MsgBox($"Config {oConfigName} does not exist!", MsgBoxStyle.Exclamation, Text)
        End Select
    End Sub

    Private Function CreateConfigTemplate(Of T)()
        Serializer = New XmlSerializer(GetType(T))
        Dim oConfig As T = Activator.CreateInstance(GetType(T))
        Dim oBytes As Byte()

        Using oStream = New MemoryStream()
            Serializer.Serialize(oStream, oConfig)
            oBytes = oStream.ToArray()
        End Using

        Return System.Text.Encoding.UTF8.GetString(oBytes)
    End Function

    Private Sub frmStart_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        SaveSettings()
    End Sub

    Private Sub SimpleButton2_Click(sender As Object, e As EventArgs) Handles SimpleButton2.Click
        Dim ActiveDir = New ActiveDirectoryInterface(LogConfig, Config.Config.EmailTemplate.ActiveDirectoryRoot)
        Dim oCustomAttributes As New List(Of AttributeMapping) From {
            New AttributeMapping With {.AttributeName = "title", .FirebirdSyskey = "", .MSSQLColumn = ""}
        }
        Dim oUsers = ActiveDir.ListUsers(Config.Config.EmailTemplate.ActiveDirectoryGroup, oCustomAttributes)
        MsgBox(oUsers.Count & " users found.", MsgBoxStyle.Information, "Yo")

        Try
            For Each oUser As ADUser In oUsers
                Dim oHtml As String = GenerateSignatureFileFromTemplate(oUser, Config.Config.EmailTemplate)
                Dim oOutputPath = Config.Config.EmailTemplate.OutputPath
                Dim oFilePath As String = Path.Combine(oOutputPath, $"Signatur-{oUser.samAccountName}.html")

                If Not Directory.Exists(oOutputPath) Then
                    Directory.CreateDirectory(oOutputPath)
                End If

                If File.Exists(oFilePath) Then
                    File.Copy(oFilePath, oFilePath & "." & Now.ToString("yyyy-MM-dd_HH-mm"), True)
                End If

                File.WriteAllText(oFilePath, oHtml)
            Next
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.Exclamation, "Signature Generator")
        End Try
    End Sub

    Private Function GenerateSignatureFileFromTemplate(User As ADUser, EmailTemplateConfig As EmailTemplateConfig)
        Dim oJobTitle = User.CustomAttributes.Where(Function(a) a.Name = "title").Single().Value

        Return EmailTemplateConfig.BaseHtml.
            Replace("__FULL_NAME__", $"{User.GivenName} {User.Surname}").
            Replace("__JOB_TITLE__", oJobTitle).
            Replace("__MAIL_ADDRESS__", User.Email).
            Replace("__BANNER_URL__", EmailTemplateConfig.BannerUrl).
            Replace("__TRACKER_URL__", EmailTemplateConfig.TrackingLink)
    End Function

    Private Sub SaveSettings()
        Config.Config.EmailTemplate.BaseHtml = txxTemplate.Text
        Config.Config.EmailTemplate.BannerUrl = txtBannerUrl.Text
        Config.Config.EmailTemplate.TrackingLink = txtTrackingUrl.Text
        Config.Config.EmailTemplate.OutputPath = txtOutputPath.Text
        Config.Config.EmailTemplate.ActiveDirectoryGroup = txtADGroup.Text
        Config.Config.EmailTemplate.ActiveDirectoryRoot = txtADRoot.Text
        Config.Save()
    End Sub

    Private Sub BarButtonItem2_ItemClick(sender As Object, e As DevExpress.XtraBars.ItemClickEventArgs) Handles BarButtonItem2.ItemClick
        SaveSettings()
    End Sub
End Class