Imports System.Xml
Imports System.IO

Public Class ClassWindowLocation
    Public Shared Sub LoadFormLocationSize(ByRef form As Form, Optional LoadSize As Boolean = True)
        Try
            Dim _path, _pathold As String

            _path = Path.Combine(Application.UserAppDataPath(), form.Name & "-Layout.xml")
            _pathold = _path.Replace("frm", "frmfrm")
            If File.Exists(_pathold) Then
                Dim newfilename = Path.GetFileName(_path)
                Try
                    My.Computer.FileSystem.RenameFile(_pathold, newfilename)
                Catch ex As Exception
                    My.Computer.FileSystem.DeleteFile(_pathold)
                End Try
                _path = Path.Combine(Application.UserAppDataPath(), form.Name & "-Layout.xml")
            End If
            Dim layout As ClassLayout = New ClassLayout(_path)
            Dim settings As System.Collections.Generic.List(Of ClassSetting)
            settings = layout.Load()

            If settings.Count = 0 Then
                settings.Add(New ClassSetting("PositionX", form.Location.X))
                settings.Add(New ClassSetting("PositionY", form.Location.Y))
                settings.Add(New ClassSetting("Width", form.Size.Width))
                settings.Add(New ClassSetting("Height", form.Size.Height))
                layout.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
                form.WindowState = FormWindowState.Maximized
            Else

                Dim rect As New Rectangle(x, y, 0, 0)
                If IsVisibleOnAnyScreen(rect) Then
                    If x >= 0 And y >= 0 Then
                        form.Location = New Point(x, y)
                    End If
                    If w > 0 And h > 0 And LoadSize = True Then
                        form.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 Shared Function IsVisibleOnAnyScreen(rect As Rectangle)
        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)
            Return False
        End Try
    End Function


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

            Dim layout As ClassLayout = New ClassLayout(_path)
            Dim settings As System.Collections.Generic.List(Of ClassSetting) = New System.Collections.Generic.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))

            layout.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
End Class


'-------------------------------------------------------------------

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

Public Class ClassLayout
    Private ReadOnly _filename As String
    Private ReadOnly _settings As XmlWriterSettings
    Private _reader As XmlReader

    Public Sub New(filename As String)
        _filename = filename

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

    Public Sub Save(settings As System.Collections.Generic.List(Of ClassSetting))
        Dim w = XmlTextWriter.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()
    End Sub

    Public Function Load() As System.Collections.Generic.List(Of ClassSetting)
        Dim Result As System.Collections.Generic.List(Of ClassSetting) = New System.Collections.Generic.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
End Class
