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 Sub RunFindNextDoc()
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  Dim iLink As IteratorLinkAll: Set iLink = theDB.FindUnresolvedLink
  If iLink Is Nothing Then
    Call UserInteraction.ShowMessage(IM_NEXTDOC_OK)
    Exit Sub
  End If
  
  Call OpenUnresolvedDocument(theDB.Data(iLink.SourceID).FileName)
End Sub

Public Sub RunCreateDummy()
  Dim gid&: gid = GetSelectedGID()
  If gid = HT03_INVALID_GID Then _
    Exit Sub
  
  If CreateDummyFor(gid) Then _
    Call UserInteraction.ShowMessage(IM_DUMMY_OK)
End Sub

Public Sub RunDeleteLaw()
  Dim gid&: gid = GetSelectedGID()
  If gid = HT03_INVALID_GID Then _
    Exit Sub
  If Not UserInteraction.AskQuestion(QM_DELETE_LAW, gid) Then _
    Exit Sub
    
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  Call DeleteLaw(gid)
  Call uiWrap.ResumeUI
  
  Call UserInteraction.ShowMessage(IM_DELETE_LAW_OK, gid)
End Sub

Public Sub RunDeleteLinks()
  Dim gid&: gid = GetSelectedGID()
  If gid = HT03_INVALID_GID Then _
    Exit Sub
  If Not UserInteraction.AskQuestion(QM_DELETE_LINKS, gid) Then _
    Exit Sub
    
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  Dim nDeleted&: nDeleted = DeleteLinks(gid)
  Call uiWrap.ResumeUI
  
  Call UserInteraction.ShowMessage(IM_DELETE_LINKS_OK, gid, nDeleted)
End Sub

Public Sub RunMergeDocument()
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  Dim iMerge As ItemMerge: Set iMerge = PromptMerge(theDB)
  If iMerge Is Nothing Then _
    Exit Sub
  If Not UserInteraction.AskQuestion(QM_MERGE_WARNING) Then _
    Exit Sub
    
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Call DeleteLaw(iMerge.delete_)
  
  Call CSE_ProgressBar.Init("Замена ссылок в документах", maxVal:=theDB.Count)
  Call CSE_ProgressBar.ShowModeless
  
  Call ExecuteMerge(iMerge)
  
  Call Unload(CSE_ProgressBar)
  Call uiWrap.ResumeUI
  
  Call UserInteraction.ShowMessage(IM_MERGE_OK, iMerge.delete_, iMerge.substitute_)
End Sub

Public Sub RunOpenGarant()
  Dim gid&: gid = GetSelectedGID()
  If gid = HT03_INVALID_GID Then _
    Exit Sub
  
  Dim hLink As New ItemHyperlink: Call hLink.Init(DEFAULT_LINK_SYSTEM, gid)
  Call UserInteraction.FollowHyperlink(ThisWorkbook, hLink.ToAddress)
End Sub

Public Sub RunExportActive()
' Generate Excel file for Registry
  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_XLOUT_CREATE_FAIL)
    Exit Sub
  End If
  
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  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 ThisWorkbook.Sheets(HT03_SHT_INFO).Copy(After:=outWB.Sheets(2))
  Call outWB.Sheets(1).Activate
  
  Call UserInteraction.ShowMessage(IM_XLOUT_OK)
End Sub

Public Sub RunStatistic()
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Call CSE_ProgressBar.Init("Обновление статистики", sHeader:="Обработка документов...", maxVal:=theDB.Count)
  Call CSE_ProgressBar.ShowModeless
  Call UpdateStats(theDB)
  Call Unload(CSE_ProgressBar)
  
  Call uiWrap.ResumeUI
  
  Call UserInteraction.ShowMessage(IM_STATS_OK)
End Sub

Public Sub RunCreateView()
  Dim xlWrap As New API_XLWrapper: Call xlWrap.SetApplication(ThisWorkbook.Application)
  Dim newUI As Excel.Workbook: Set newUI = xlWrap.NewDocument(VIEW_TEMPLATE_PATH, bDefaultIfFail:=False)
  If newUI Is Nothing Then _
    Exit Sub
  
  Call newUI.Activate
  Call xlWrap.Run("SetDB", ThisWorkbook.FullName)
End Sub

Public Sub RunUpdateFirstLink()
  Dim uiWrap As New API_XLWrapper: Call uiWrap.SetDocument(ThisWorkbook)
  Call uiWrap.PauseUI
  
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  Call CSE_ProgressBar.Init("Обновление индекса", maxVal:=theDB.CountLinks)
  Call CSE_ProgressBar.ShowModeless
  Dim sMsg$: sMsg = theDB.ValidateLinks
  Call Unload(CSE_ProgressBar)
  
  Call uiWrap.ResumeUI
  
  If sMsg = vbNullString Then
    Call UserInteraction.ShowMessage(IM_RECREATE_OK)
  Else
    Call UIShowMessage(EM_LINKBASE_FAILED, sMsg)
  End If
End Sub

Public Sub RunRename()
  Dim gid&: gid = GetSelectedGID()
  If gid = HT03_INVALID_GID Then _
    Exit Sub
  
  Dim theDB As InfoDatabase: Set theDB = AccessDatabase
  Dim sName$: sName = PromptNewFileName(gid, theDB)
  If sName = vbNullString Then _
    Exit Sub

  If Not theDB.RenameLawFile(gid, sName) Then
    Call UserInteraction.ShowMessage(EM_RENAME_FAILED, gid, sName)
  Else
    Call UserInteraction.ShowMessage(IM_RENAME_COMPLETE, gid, sName)
  End If
End Sub

Public Sub RunHyperlinks()
  Call UpdateHyperlinks(Sheets(HT03_SHT_DOCS), AccessDatabase)
  Call UserInteraction.ShowMessage(IM_HYPERLINKS_OK)
End Sub

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

Public Sub RunHelp()
  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

' ====
Private Function GetSelectedGID() As Long
  GetSelectedGID = HT03_INVALID_GID
  Dim sel As Excel.Range: Set sel = Excel.Selection
  Dim docsSht As Excel.Worksheet: Set docsSht = Sheets(HT03_SHT_DOCS)
  
  Dim selTxt$: selTxt = sel.Cells(1, 1)
  If IsNumeric(selTxt) And ActiveSheet.Name <> docsSht.Name Then
    GetSelectedGID = CLng(selTxt)
    Exit Function
  End If
  
  Dim gid&: gid = CLng(docsSht.Cells(sel.Cells(1, 1).Row, 1))
  If ActiveSheet.Name <> docsSht.Name Or sel.Rows.Count > 1 Or gid = 0 Then
    Dim resStr$: resStr = UserInteraction.PromptInput("Введите ID документа")
    If resStr = vbNullString Or Not IsNumeric(resStr) Then _
      Exit Function
    gid = CLng(resStr)
  End If
  GetSelectedGID = gid
End Function
