Attribute VB_Name = "Main"
Option Explicit

Public Const PRODUCT_VERSION = "1.3.0"
Public Const PRODUCT_NAME = "Concept-NPA"

Public g_VersionTimer As Long

Public Sub Auto_Open()
  Dim sCmd$: sCmd = OfficeCommandLine
  If VBA.InStr(1, sCmd, "/automation", vbTextCompare) <> 0 Then _
    Exit Sub
  
  g_VersionTimer = SetTimer(0, 0, CP_VERSION_MSG_DELAY, AddressOf OnVersionCheck)
End Sub

Public Function OnVersionCheck(ByVal nHwnd As Long, ByVal uMsg As Long, ByVal nEvent As Long, ByVal nTime As Long)
  Call KillTimer(0, g_VersionTimer)
  Call VersionValidate(PRODUCT_NAME, PRODUCT_VERSION)
End Function

Public Function SetDB(sFile$)
  ThisWorkbook.Names(VIEW_CELL_DBPATH).RefersToRange = sFile
  Call RunUpdate
End Function

Public Sub RunSetDB()
  Dim sFileName$: sFileName = UserInteraction.PromptFileFilter(ThisWorkbook.Path, _
                                                sDescription:="Таблица Excel", _
                                                sFilter:="*.xlsx;*.xls;*.xlsm")
  If sFileName = vbNullString Then _
    Exit Sub
  If sFileName = ThisWorkbook.Names(VIEW_CELL_DBPATH).RefersToRange Then _
    Exit Sub
  
  Call SetDB(sFileName)
End Sub

Public Sub RunUpdate()
  Dim dbInput As API_XLWrapper: Set dbInput = AccessDatabase()
  If dbInput Is Nothing Then _
    Exit Sub
  
  Call ClearData
  Dim iSource As New InfoDatabase: Call iSource.Init(dbInput.Document, GetDocumentsLocation(dbInput.Document))
  Call ImportData(iSource, AccessLocal)
  Call dbInput.ReleaseDocument
  
  Call ThisWorkbook.Sheets(SHT_START).Activate
  Call UserInteraction.ShowMessage(IM_IMPORT_SUCCESS)
End Sub

Public Sub RunAddLaw()
  Dim sFile$: sFile = UserInteraction.PromptFile(ThisWorkbook.Path)
  If sFile = vbNullString Then _
    Exit Sub
    
  Dim wrapper As New API_WordWrapper
  If wrapper.OpenDocument(sFile, bReadOnly:=True) Is Nothing Then _
    Exit Sub
  
  Dim bSuccess As Boolean: bSuccess = ProposeNewDocument(wrapper.Document, AccessLocal)
  Call wrapper.ReleaseDocument
  
  If bSuccess Then _
    Call UserInteraction.ShowMessage(IM_NEW_DOC_SUCCESS)
End Sub

Public Sub RunLoadLinkText()
  If Not UserInteraction.AskQuestion(QM_LOAD_TEXTS) Then _
    Exit Sub
  
  Dim lnks As Excel.Worksheet: Set lnks = ThisWorkbook.Sheets(SHT_OUT_LINKS)
  Dim localData As InfoDatabase: Set localData = AccessLocal
  
  Call CSE_ProgressBar.Init("Обработка ссылок", maxVal:=lnks.UsedRange.Rows.Count - HT03_DEFAULT_FIRST_LINE - 1, canInterrupt:=True)
  Call CSE_ProgressBar.ShowModeless
  Call localData.StartOptimization
  
  Call LoadTextsForLinks(localData, lnks)
  
  Call localData.EndOptimization
  Call Unload(CSE_ProgressBar)
  
  Call UserInteraction.ShowMessage(IM_LOAD_TEXT_SUCCESS)
End Sub

Public Sub RunUnstuck()
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.ResumeUI
  Call UserInteraction.ShowMessage(IM_UNSTUCK_SUCCESS)
End Sub

Public Sub RunClearData()
  If UserInteraction.AskQuestion(QM_CLEAR_IMPORTED_DATA) Then
    Call ClearData
    Call UserInteraction.ShowMessage(IM_CLEAR_SUCCESS)
  End If
End Sub

Public Sub RunClearAll()
  If UserInteraction.AskQuestion(QM_CLEAR_DATA) Then
    Call ClearData
    Call ClearQueryLinks
    Call ClearQueryDocs
  End If
End Sub

Public Sub RunExportData()
' Create Excel export for visualization and further processing
  Dim xlApp As New API_XLWrapper
  Call xlApp.SetApplication(ThisWorkbook.Parent)
  Dim outWB As Excel.Workbook: Set outWB = xlApp.NewDocument
  If outWB Is Nothing Then
    Call UserInteraction.ShowMessage(EM_FAILED_OUTPUT_CREATION)
    Exit Sub
  End If
  
  Dim theDB As InfoDatabase: Set theDB = AccessLocal
  Call CSE_ProgressBar.Init("Выгрузка данных", maxVal:=theDB.Count + theDB.CountLinks)
  Call CSE_ProgressBar.InitSecondBar(maxVal:=theDB.Count)
  CSE_ProgressBar.Description = "Список документов"
  Call CSE_ProgressBar.ShowModeless

  Call xlApp.PauseUI
  Call Output2Excel(outWB, theDB)
  Call xlApp.ResumeUI
  
  Call Unload(CSE_ProgressBar)

  Call UserInteraction.ShowMessage(IM_EXPORT_SUCCESS)
End Sub

Public Sub RunQueryLawsVisible()
  Call ClearQueryDocs
  
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLaws: Call iFilter.Init(GetVisibleLaws())
  Call theMaster.QueryLaws(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_DOCS).Activate
End Sub

Public Sub RunQueryLawsOnce()
  Dim iSelected As Scripting.Dictionary: Set iSelected = GetQueryDocsArgument(g_UIState.source_)
  If iSelected Is Nothing Then _
    Exit Sub
  
  Call GraphExpandOnce(iSelected, g_UIState.linkType_, g_UIState.direction_)
  
  Call ClearQueryDocs
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLaws: Call iFilter.Init(iSelected)
  Call theMaster.QueryLaws(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_DOCS).Activate
End Sub

Public Sub RunQueryLawsFull()
  Dim iSelected As Scripting.Dictionary: Set iSelected = GetQueryDocsArgument(g_UIState.source_)
  If iSelected Is Nothing Then _
    Exit Sub
  
  Call GraphExpandFull(iSelected, g_UIState.linkType_, g_UIState.direction_)
  
  Call ClearQueryDocs
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLaws: Call iFilter.Init(iSelected)
  Call theMaster.QueryLaws(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_DOCS).Activate
End Sub

Public Sub RunLinksVisible()
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Dim lnkRows As Collection: Set lnkRows = VisibleLinkRows()
  Call ClearQueryLinks
  
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLinkRow: Call iFilter.Init(lnkRows)
  Call theMaster.QueryLinks(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_LINKS).Activate
  
  Call uiWrap.ResumeUI
End Sub

Public Sub RunQueryLinksLaw()
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Dim iSelected As Scripting.Dictionary: Set iSelected = GetQueryDocsArgument(g_UIState.source_)
  If iSelected Is Nothing Then _
    Exit Sub
  
  Call ClearQueryLinks
  
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLinkComplex: Call iFilter.Init(iSelected, g_UIState.linkType_, g_UIState.direction_, onlyInternal:=False)
  Call theMaster.QueryLinks(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_LINKS).Activate
  
  Call uiWrap.ResumeUI
End Sub

Public Sub RunQueryLinksInternal()
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Dim iSelected As Scripting.Dictionary: Set iSelected = GetQueryDocsArgument(g_UIState.source_)
  If iSelected Is Nothing Then _
    Exit Sub
  
  Call ClearQueryLinks
  
  Dim theMaster As New QueryMaster: Call theMaster.Init(AccessLocal())
  Dim iFilter As New QFilterLinkComplex: Call iFilter.Init(iSelected, g_UIState.linkType_, g_UIState.direction_, onlyInternal:=True)
  Call theMaster.QueryLinks(iFilter)
  
  Call ThisWorkbook.Sheets(SHT_OUT_LINKS).Activate
  
  Call uiWrap.ResumeUI
End Sub

Public Sub RunHelp()
' Open help file
  Dim wordWrap As New API_WordWrapper
  Dim helpDoc As Word.Document: Set helpDoc = wordWrap.OpenDocument(HELP_FILE_PATH, bReadOnly:=True)
  If helpDoc Is Nothing Then _
    Exit Sub
  With helpDoc
    .Application.ActiveWindow.View.ReadingLayout = False
    Call .ActiveWindow.ScrollIntoView(helpDoc.Bookmarks(HELP_BOOKMARK).Range)
    Call .Application.Activate
  End With
End Sub

Public Sub RunOpenLawsLocation()
  Dim oShell As New Shell32.Shell
  Call oShell.Open(AccessLocal().docsLocation_)
End Sub

Public Function GetDocumentLevel(rType As TLawType) As Long
  GetDocumentLevel = DefaultLawLevelFor(rType)
End Function

' =================
Private Function GetQueryDocsArgument(nSourceType As TLawSource) As Scripting.Dictionary
  Select Case nSourceType
    Case T_LS_SELECTED: Set GetQueryDocsArgument = GetSelectedLaws
    Case T_LS_VISIBLE: Set GetQueryDocsArgument = GetVisibleLaws
    Case T_LS_FROM_ID
      Dim sInput$: sInput = UserInteraction.PromptInput("Введите ID документа")
      If sInput = vbNullString Or Not IsNumeric(sInput) Then
        Call UserInteraction.ShowMessage(EM_INVALID_QUERY_INPUT)
        Exit Function
      End If
      Dim gid&: gid = CLng(sInput)
      If Not AccessLocal.Contains(gid) Then
        Call UserInteraction.ShowMessage(EM_ID_NOT_FOUND)
        Exit Function
      End If
      Set GetQueryDocsArgument = New Scripting.Dictionary
      Call GetQueryDocsArgument.Add(gid, 0)
  End Select
End Function

