' *
' * The project site is at: http://code.google.com/p/fishbornas/
' *
' * First author tiritomato 2012.
' *
' * Distributed under the FishbornArchiveShelf License (See
' *  http://fishbornas.googlecode.com/svn/trunk/Licenses/License.txt)
' *
' * 2012.06.07 Initial Revision (tiritomato)
' *

Module MainModule

    Private ReadOnly CommandlineParameterSet As Logic.CommandlineParser.Arguments.SplitInfo = {
        New Logic.CommandlineParser.Arguments.NamedParameterInfo("r"c, "rar", 1),
        New Logic.CommandlineParser.Arguments.NamedParameterInfo("h"c, {"lh", "limitheight"}, 1),
        New Logic.CommandlineParser.Arguments.NamedParameterInfo("w"c, {"lw", "limitwidth"}, 1),
        New Logic.CommandlineParser.Arguments.NamedParameterInfo("c"c, {"ct", "count"}, 1),
        New Logic.CommandlineParser.Arguments.NamedParameterInfo("d"c, "dbg", 0)
    }

    Private ctSampling As Integer = 10
    Private isDebug As Boolean = False
    Private nLimitHeight As Integer = -1
    Private nLimitWidth As Integer = -1
    Private strRarPath As String = ""
    Private strArcPath As String = ""

    Function Main(ByVal aryCmdArgs() As String) As Integer

#If DEBUG Then
        MsgBox("Picker Start")
#End If

        Try
            Dim SplitArgs As New Logic.CommandlineParser.Arguments.Parameter.Collection(CommandlineParameterSet, aryCmdArgs)
            If 0 < SplitArgs("r"c).Params.Count Then strRarPath = SplitArgs("r"c).Params(0)
            If SplitArgs("w"c).Params.Count <= SplitArgs("h"c).Params.Count Then
                nLimitHeight = SplitArgs("h"c).Params(0)
            ElseIf 0 < SplitArgs("w"c).Params.Count Then
                nLimitWidth = SplitArgs("w"c).Params(0)
            End If
            If 0 < SplitArgs("c"c).Params.Count Then ctSampling = SplitArgs("c"c).Params(0)
            If 0 < SplitArgs("d"c).Exists Then isDebug = True
            If 0 < SplitArgs(vbNullChar).Params.Count Then
                For Each arg As String In SplitArgs(vbNullChar).Params
                    If IO.File.Exists(arg) Then
                        strArcPath = arg
                        Exit For
                    End If
                Next
            End If
        Catch ex As Exception
            Return AppBase.RESULT.INVALID_BOOT_OPTION
        End Try

        Dim Config As AppBase.ArchiveOptionConfig = AppBase.ArchiveOptionConfigCollection.ArchiveOptionConfig(strArcPath)
        If Config Is Nothing Then Return AppBase.RESULT.INVALID_FILE_EXT
        Dim p As AppBase.ArchiveProcess = Config.CreateProcess

        Dim ExtSelecter As New Logic.FileSystem.Extention.Collection(Logic.Graphics.GDIPlusExtentions)
        AppBase.Archive.RarOptionConfig.RarPath = strRarPath

        Dim strExt As String = New Logic.FileSystem.Path(strArcPath).Extention.ToString

        Main = AppBase.RESULT.OK

        If p Is Nothing Then
            Main = AppBase.RESULT.INVALID_FILE_EXT
        Else
            Dim entries() As String = Nothing
            Main = p.GetEntryList(entries, strArcPath)
            If Main = AppBase.RESULT.OK Then

                Dim SelectedEntries As Collections.Generic.List(Of String) = Logic.FileSystem.Path.GetIntersectCollection(entries, ExtSelecter)
                entries = Nothing
                If SelectedEntries IsNot Nothing AndAlso 0 < SelectedEntries.Count Then
                    entries = Logic.Math.Statistics.GetDawnSampling(SelectedEntries.ToArray, ctSampling)
                End If

                If entries IsNot Nothing AndAlso 0 < entries.Length Then

                    Dim size_list As New Collections.Generic.List(Of Drawing.Size)(entries.Length)
                    For Each entry As String In entries
                        Dim hBuf As IO.MemoryStream = Nothing
                        Dim ret As AppBase.RESULT = p.Extract(hBuf, entry, strArcPath)
                        Select Case ret
                            Case AppBase.RESULT.OK
                                Dim sz As Drawing.Size = GetImageSizeFromStream(hBuf)
                                If Not sz.IsEmpty Then
                                    size_list.Add(sz)
                                    Console.Out.WriteLine(String.Format("{0} : ({1}x{2})", entry, sz.Width, sz.Height))
                                End If
                            Case Else
                                Console.Out.WriteLine(String.Format("{0} : {1}", entry, AppBase.ResultMessage(ret)))
                        End Select
                        If Not hBuf Is Nothing Then hBuf.Close()
                    Next

                    If 0 < size_list.Count Then

                        Dim width_list(size_list.Count - 1) As Integer
                        Dim height_list(size_list.Count - 1) As Integer

                        For idx As Integer = 0 To size_list.Count - 1
                            width_list(idx) = size_list(idx).Width
                            height_list(idx) = size_list(idx).Height
                        Next

                        Dim WidthHistogram As New Logic.Math.Statistics.AutoHistogram(Of Integer)(width_list)
                        Dim HeightHistogram As New Logic.Math.Statistics.AutoHistogram(Of Integer)(height_list)
                        Dim Average As Drawing.Size

                        If WidthHistogram.ModeBins Is Nothing OrElse WidthHistogram.ModeBins.Count <= 0 Then
                            Average.Width = Logic.Math.Average(width_list)
                        Else
                            Average.Width = WidthHistogram.ModeBins.Average
                        End If

                        If HeightHistogram.ModeBins Is Nothing OrElse HeightHistogram.ModeBins.Count <= 0 Then
                            Average.Height = Logic.Math.Average(height_list)
                        Else
                            Average.Height = HeightHistogram.ModeBins.Average
                        End If

                        Console.Out.WriteLine(String.Format("ModeAverage : ({0}x{1})", Average.Width, Average.Height))

                        If 0 <= nLimitHeight And nLimitHeight <= Average.Height Then Main = AppBase.RESULT.EXECUTE
                        If 0 <= nLimitWidth And nLimitWidth <= Average.Width Then Main = AppBase.RESULT.EXECUTE

                    Else
                        Main = AppBase.RESULT.OK ' Ok is ignore file
                    End If

                End If

            End If

        End If

        Console.Out.WriteLine(String.Format("({0}) {1}", Main, IIf(Main = AppBase.RESULT.OK, "Target File", AppBase.ResultMessage(Main))))
#If DEBUG Then
        MsgBox("Finished")
#End If

    End Function

    Private Function GetImageSizeFromStream(ByVal hBuf As IO.Stream) As Drawing.Size

        Dim objImg As Drawing.Image = Nothing
        GetImageSizeFromStream = Nothing
        Try
            objImg = Drawing.Image.FromStream(hBuf)
            If 0 < objImg.Width And objImg.Height Then
                GetImageSizeFromStream.Width = objImg.Width
                GetImageSizeFromStream.Height = objImg.Height
            End If
        Catch ex As Exception
            GetImageSizeFromStream = Nothing
        Finally
            If Not objImg Is Nothing Then objImg.Dispose()
        End Try

    End Function

End Module
