Attribute VB_Name = "KikiLivePhoto"
Option Explicit

' Kiki LivePhoto - module VBA dung chung cho moi giao an (1-6 doi).
' Helper goi KikiDispatch qua Apple Events (macOS) hoac COM (Windows). VBA chi chay ngan theo lenh.
' Khung anh: hinh chu nhat co ten LivePhoto_1 .. LivePhoto_N tren DUNG MOT slide, fill tron.

Private Const MaxTeams As Long = 6
Private currentRun As String
Private liveSlide As Slide
Private teamCount As Long
Private frames(1 To 6) As Shape
Private picturePaths(1 To 6) As String
Private originalColor(1 To 6) As Long
Private originalTransparency(1 To 6) As Single
Private originalVisibility(1 To 6) As MsoTriState
Private filledMask As Long
Private liveDeck As Presentation
Private dirtyAfterApply As Boolean

' Ma tra ve: 100 probe, 110 prepare, 200+ apply, 300/301 stop, 410/411 status, size = rong*10000+cao.
' Loi: -10 khong thay giao an, -11..-18 xem README, -20..-26 cau truc khung, -15 loi VBA.
Public Function KikiDispatch(ByVal operation As String, ByVal runID As String, ByVal deckName As String, _
                             ByVal firstValue As String, ByVal secondValue As String) As Long
    Dim deck As Presentation
    On Error GoTo Failed
    Set deck = FindDeck(deckName)
    If deck Is Nothing Then
        KikiDispatch = -10
        Exit Function
    End If

    Select Case operation
        Case "probe"
            KikiDispatch = 100
        Case "prepare"
            KikiDispatch = Prepare(deck, runID, firstValue, secondValue)
        Case "size"
            If Len(currentRun) = 0 Or currentRun <> runID Then
                KikiDispatch = -13
            Else
                KikiDispatch = FrameSize(CLng(firstValue))
            End If
        Case "apply"
            If Len(currentRun) = 0 Or currentRun <> runID Then
                KikiDispatch = -13
            Else
                KikiDispatch = ApplyChanges(deck, CLng(firstValue), secondValue = "1")
            End If
        Case "status"
            CleanIfSaved
            If IsShowing(deck) Then
                KikiDispatch = 410
            Else
                KikiDispatch = 411
            End If
        Case "stop"
            KikiDispatch = 301
            If Len(currentRun) > 0 And currentRun = runID Then
                If filledMask <> 0 Then
                    RestoreFrames
                    If secondValue = "1" Then Call RefreshIfShowing(deck)
                End If
                ResetState
                KikiDispatch = 300
            End If
        Case Else
            KikiDispatch = -14
    End Select
    Exit Function

Failed:
    KikiDispatch = -15
End Function

Private Sub ResetState()
    Dim index As Long
    Set liveDeck = Nothing
    dirtyAfterApply = False
    currentRun = vbNullString
    teamCount = 0
    filledMask = 0
    Set liveSlide = Nothing
    For index = 1 To MaxTeams
        Set frames(index) = Nothing
    Next index
End Sub

' Tim dung mot giao an dang mo theo ten file. Trung ten -> Nothing.
Private Function FindDeck(ByVal deckName As String) As Presentation
    Dim deck As Presentation
    Dim found As Presentation
    If Len(deckName) = 0 Then Exit Function
    For Each deck In Application.Presentations
        If StrComp(deck.Name, deckName, vbTextCompare) = 0 Then
            If Not found Is Nothing Then Exit Function
            Set found = deck
        End If
    Next deck
    Set FindDeck = found
End Function

Private Function Prepare(ByVal deck As Presentation, ByVal runID As String, _
                         ByVal countText As String, ByVal pathList As String) As Long
    Dim candidate As Slide
    Dim frame As Shape
    Dim paths() As String
    Dim seen(1 To 6) As Boolean
    Dim found(1 To 6) As Shape
    Dim foundCount As Long
    Dim number As Long
    Dim suffix As String
    Dim index As Long
    Dim grantList() As Variant

    If Len(currentRun) > 0 Then
        Prepare = -17
        Exit Function
    End If
    If Not IsNumeric(countText) Then
        Prepare = -18
        Exit Function
    End If
    teamCount = CLng(countText)
    If teamCount < 1 Or teamCount > MaxTeams Then
        teamCount = 0
        Prepare = -18
        Exit Function
    End If
    paths = Split(pathList, "|")
    If UBound(paths) <> teamCount - 1 Then
        teamCount = 0
        Prepare = -18
        Exit Function
    End If

    Set liveSlide = Nothing
    Prepare = -20
    For Each candidate In deck.Slides
        foundCount = 0
        For index = 1 To MaxTeams
            seen(index) = False
            Set found(index) = Nothing
        Next index
        For Each frame In candidate.Shapes
            If Left$(frame.Name, 10) = "LivePhoto_" Then
                suffix = Mid$(frame.Name, 11)
                If Not IsNumeric(suffix) Then
                    Prepare = -24
                    GoTo Rejected
                End If
                number = CLng(suffix)
                If CStr(number) <> suffix Or number < 1 Or number > teamCount Then
                    Prepare = -24
                    GoTo Rejected
                End If
                If seen(number) Then
                    Prepare = -22
                    GoTo Rejected
                End If
                seen(number) = True
                Set found(number) = frame
                foundCount = foundCount + 1
            End If
        Next frame
        If foundCount > 0 Then
            If Not liveSlide Is Nothing Then
                Prepare = -23
                GoTo Rejected
            End If
            If foundCount <> teamCount Then
                Prepare = -21
                GoTo Rejected
            End If
            Set liveSlide = candidate
            For index = 1 To teamCount
                Set frames(index) = found(index)
            Next index
        End If
    Next candidate
    If liveSlide Is Nothing Then GoTo Rejected

    For index = 1 To teamCount
        With frames(index).Fill
            If .Type <> msoFillSolid Then
                Prepare = -26
                GoTo Rejected
            End If
            originalColor(index) = .ForeColor.RGB
            originalTransparency(index) = .Transparency
            originalVisibility(index) = .Visible
        End With
    Next index

#If Mac Then
    ReDim grantList(0 To teamCount - 1)
    For index = 1 To teamCount
        grantList(index - 1) = paths(index - 1)
    Next index
    If Not GrantAccessToMultipleFiles(grantList) Then
        Prepare = -12
        GoTo Rejected
    End If
#End If
    For index = 1 To teamCount
        picturePaths(index) = paths(index - 1)
    Next index
    currentRun = runID
    filledMask = 0
    Set liveDeck = deck
    dirtyAfterApply = False
    Prepare = 110
    Exit Function

Rejected:
    Set liveSlide = Nothing
    For index = 1 To MaxTeams
        Set frames(index) = Nothing
    Next index
    teamCount = 0
End Function

' Chieu rong x 10000 + chieu cao (diem, lam tron) de helper dung anh dung ti le khung.
Private Function FrameSize(ByVal index As Long) As Long
    If index < 1 Or index > teamCount Then
        FrameSize = -16
        Exit Function
    End If
    FrameSize = CLng(frames(index).Width + 0.5) * 10000 + CLng(frames(index).Height + 0.5)
End Function

' changes: bit 1..6 = cap nhat khung, bit 7..12 = tra khung ve mau trong.
Private Function ApplyChanges(ByVal deck As Presentation, ByVal changes As Long, _
                              ByVal redraw As Boolean) As Long
    Dim index As Long
    Dim bit As Long
    Dim updated As Long
    Dim updateMask As Long
    Dim clearMask As Long

    ApplyChanges = -16
    If changes < 1 Or changes > 4095 Then Exit Function
    updateMask = changes And 63
    clearMask = changes \ 64
    If (updateMask And clearMask) <> 0 Then Exit Function
    If ((updateMask Or clearMask) \ (2 ^ teamCount)) <> 0 Then Exit Function

    For index = 1 To teamCount
        bit = 2 ^ (index - 1)
        If (updateMask And bit) <> 0 Then
            ' Danh dau khung da cham toi ngay ca khi UserPicture loi giua chung.
            filledMask = filledMask Or bit
            frames(index).Fill.Visible = msoTrue
            frames(index).Fill.UserPicture picturePaths(index)
            updated = updated Or bit
        ElseIf (clearMask And bit) <> 0 Then
            RestoreFrame index
            updated = updated Or bit
        End If
    Next index

    ' 200 + ma khung (toi da 63) -> 200..263; +1000 neu da ve lai slide dang chieu.
    dirtyAfterApply = (deck.Saved = msoFalse)
    ApplyChanges = 200 + updated
    If redraw Then
        If RefreshIfShowing(deck) Then ApplyChanges = ApplyChanges + 1000
    End If
End Function

Private Sub RestoreFrames()
    Dim index As Long
    For index = 1 To teamCount
        If (filledMask And (2 ^ (index - 1))) <> 0 Then RestoreFrame index
    Next index
End Sub

Private Sub RestoreFrame(ByVal index As Long)
    With frames(index).Fill
        .Solid
        .ForeColor.RGB = originalColor(index)
        .Transparency = originalTransparency(index)
        .Visible = originalVisibility(index)
    End With
    filledMask = filledMask And Not CLng(2 ^ (index - 1))
End Sub

Private Function IsShowing(ByVal deck As Presentation) As Boolean
    Dim window As SlideShowWindow
    For Each window In Application.SlideShowWindows
        If window.Presentation Is deck Then
            If window.View.State = ppSlideShowRunning Then
                IsShowing = True
                Exit Function
            End If
        End If
    Next window
End Function

' Chi ve lai khi dung slide LivePhoto dang duoc chieu. Giu nguyen animation va focus.
Private Function RefreshIfShowing(ByVal deck As Presentation) As Boolean
    Dim window As SlideShowWindow
    If liveSlide Is Nothing Then Exit Function
    For Each window In Application.SlideShowWindows
        If window.Presentation Is deck Then
            With window.View
                If .State = ppSlideShowRunning And .Slide.SlideID = liveSlide.SlideID Then
                    .GotoSlide liveSlide.SlideIndex, msoFalse
                    RefreshIfShowing = True
                    Exit Function
                End If
            End With
        End If
    Next window
End Function

' Phat hien giao an vua duoc luu khi con anh doi (Saved chuyen False -> True sau lan apply):
' tra khung ve mau goc, luu lai ban sach roi dat lai anh. Chay trong lenh "status" cua helper.
Private Sub CleanIfSaved()
    Dim index As Long
    Dim bit As Long
    Dim mask As Long
    If Len(currentRun) = 0 Or liveDeck Is Nothing Then Exit Sub
    If filledMask = 0 Or Not dirtyAfterApply Then Exit Sub
    If liveDeck.Saved <> msoTrue Then Exit Sub
    mask = filledMask
    RestoreFrames
    liveDeck.Save
    For index = 1 To teamCount
        bit = 2 ^ (index - 1)
        If (mask And bit) <> 0 Then
            filledMask = filledMask Or bit
            frames(index).Fill.Visible = msoTrue
            frames(index).Fill.UserPicture picturePaths(index)
        End If
    Next index
    dirtyAfterApply = (liveDeck.Saved = msoFalse)
End Sub
