Imports System.Xml
Imports System.IO
Imports DigitalData.Modules.Logging
Public Class ClassWindowLayout
    Inherits Base.BaseClass

    Private _FileName As String
    Private _Reader As XmlReader
    Private _Settings As XmlWriterSettings

    Public Sub New(pLogConfig As LogConfig)
        MyBase.New(pLogConfig)

        _Settings = New XmlWriterSettings With {
            .Encoding = Text.Encoding.UTF8,
            .Indent = True
        }
    End Sub

    Public Sub LoadFormLocationSize(ByRef pForm As Form, Optional pLoadSize As Boolean = True)
        Try
            Dim oPath, oAlternatePath As String

            oPath = Path.Combine(Application.UserAppDataPath(), pForm.Name & "-Layout.xml")
            oAlternatePath = oPath.Replace("frm", "frmfrm")

            If File.Exists(oAlternatePath) Then
                Dim oNewFilename = Path.GetFileName(oPath)

                Try
                    My.Computer.FileSystem.RenameFile(oAlternatePath, oNewFilename)
                Catch ex As Exception
                    Logger.Error(ex)
                    My.Computer.FileSystem.DeleteFile(oAlternatePath)

                End Try

                oPath = Path.Combine(Application.UserAppDataPath(), pForm.Name & "-Layout.xml")
            End If
            _FileName = oPath

            Dim settings As List(Of ClassSetting)
            settings = Load()

            If settings.Count = 0 Then
                settings.Add(New ClassSetting("PositionX", pForm.Location.X))
                settings.Add(New ClassSetting("PositionY", pForm.Location.Y))
                settings.Add(New ClassSetting("Width", pForm.Size.Width))
                settings.Add(New ClassSetting("Height", pForm.Size.Height))
                Save(settings)
            End If
            Dim x, y, w, h As Integer
            For Each s As ClassSetting In settings
                'MsgBox(s._name & vbNewLine & s._value)
                Select Case s._name
                    Case "PositionX"
                        x = Integer.Parse(s._value)
                    Case "PositionY"
                        y = Integer.Parse(s._value)
                    Case "Width"
                        w = Integer.Parse(s._value)
                    Case "Height"
                        h = Integer.Parse(s._value)
                End Select
            Next
            Dim screenWidth As Integer = Screen.PrimaryScreen.Bounds.Width
            Dim screenHeight As Integer = Screen.PrimaryScreen.Bounds.Height
            If x = 5000 Then
                pForm.WindowState = FormWindowState.Maximized
            Else

                Dim rect As New Rectangle(x, y, 0, 0)
                If IsVisibleOnAnyScreen(rect) Then
                    If x >= 0 And y >= 0 Then
                        pForm.Location = New Point(x, y)
                    End If
                    If w > 0 And h > 0 And pLoadSize = True Then
                        pForm.Size = New Size(w, h)
                    End If
                End If
                ' form.Size = New Size(310, 190)


            End If
        Catch notFoundEx As System.IO.FileNotFoundException

        Catch ex As Exception
            MsgBox("Error while loading Window Position!" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try
    End Sub
    Private Function IsVisibleOnAnyScreen(rect As Rectangle) As Boolean
        Try
            Dim result As Boolean = False
            For Each Screen As Screen In Screen.AllScreens
                If Screen.WorkingArea.IntersectsWith(rect) Then
                    result = True
                End If
            Next
            If result = False Then
                Logger.Info(">> Saved layout is not fitting to Resolution. Default is loaded.")
            End If
            Return result
        Catch ex As Exception
            Logger.Info("Error in IsVisibleOnAnyScreen: " & ex.Message)
            Logger.Error(ex.Message)
            Return False
        End Try
    End Function


    Public Sub SaveFormLocationSize(ByRef form As Form)
        Try
            Dim _path As String
            _path = Path.Combine(Application.UserAppDataPath(), form.Name & "-Layout.xml")

            Dim settings As List(Of ClassSetting) = New List(Of ClassSetting)
            Dim width As Integer
            Dim height As Integer
            Dim x As Integer
            Dim y As Integer
            If form.WindowState = FormWindowState.Maximized Then
                width = 5000
                height = 5000
                x = 5000
                y = 5000
            Else
                width = form.Size.Width
                height = form.Size.Height
                x = form.Location.X
                y = form.Location.Y
            End If

            settings.Add(New ClassSetting("PositionX", x))
            settings.Add(New ClassSetting("PositionY", y))
            settings.Add(New ClassSetting("Width", width))
            settings.Add(New ClassSetting("Height", height))

            Save(settings)
        Catch notFoundEx As System.IO.FileNotFoundException

        Catch ex As Exception
            MsgBox("Error while saving Window Positions:" & vbNewLine & ex.Message, MsgBoxStyle.Critical)
        End Try


    End Sub

    Public Sub Save(settings As System.Collections.Generic.List(Of ClassSetting))
        Try
            Dim w = XmlWriter.Create(_FileName, _Settings)

            w.WriteStartDocument()
            w.WriteStartElement("Settings")

            For Each setting As ClassSetting In settings
                w.WriteStartElement("Setting")
                w.WriteAttributeString("name", setting._name)
                w.WriteAttributeString("value", setting._value.ToString())
                w.WriteEndElement()
            Next

            w.WriteEndElement()
            w.WriteEndDocument()

            w.Dispose()
            w.Close()
        Catch ex As Exception
            Logger.Error(ex)
        End Try
    End Sub

    Public Function Load() As List(Of ClassSetting)
        Dim Result As List(Of ClassSetting) = New List(Of ClassSetting)()

        If Not File.Exists(_FileName) Then
            Return Result
        End If

        _Reader = XmlReader.Create(_FileName)

        While _Reader.Read()
            If _Reader.IsStartElement() Then
                If _Reader.Name = "Setting" Then
                    Dim name As String = _Reader("name")
                    Dim value As Integer = Integer.Parse(_Reader("value"))
                    Dim setting As ClassSetting = New ClassSetting(name, value)
                    Result.Add(setting)
                End If
            End If
        End While

        _Reader.Dispose()
        _Reader.Close()

        Return Result
    End Function

    Public Class ClassSetting
        Public _name As String
        Public _value As Integer

        Public Sub New(name As String, value As Integer)
            _name = name
            _value = value
        End Sub
    End Class
End Class