1module Matterhorn.State.SaveAttachmentWindow
2  ( openSaveAttachmentWindow
3  )
4where
5
6import           Prelude ()
7import           Matterhorn.Prelude
8import           Brick.Widgets.List ( listSelectedElement )
9
10import           Lens.Micro.Platform ( (.=), to )
11
12import           Network.Mattermost.Types ( fileInfoName )
13import           Network.Mattermost.Endpoints ( mmGetMetadataForFile )
14
15import           Matterhorn.Types
16import           Matterhorn.State.Common
17
18
19-- | If the currently selected link in the URL list is for an
20-- attachment, open a window to get the user to provide a path to which
21-- to save the attachment. If the URL list is empty or if the selected
22-- entry is not for an attachment, this returns to the Main mode but
23-- otherwise does nothing.
24openSaveAttachmentWindow :: MH ()
25openSaveAttachmentWindow = do
26    selected <- use (csCurrentTeam.tsUrlList.to listSelectedElement)
27    case selected of
28        Nothing -> return ()
29        Just (_, (_, link)) ->
30            case link^.linkTarget of
31                LinkFileId fId -> do
32                    tId <- use csCurrentTeamId
33                    session <- getSession
34                    doAsyncWith Normal $ do
35                        info <- mmGetMetadataForFile fId session
36                        return $ Just $ do
37                            csCurrentTeam.tsSaveAttachmentDialog .= newSaveAttachmentDialog tId (fileInfoName info)
38                            setMode $ SaveAttachmentWindow link
39                _ ->
40                    -- The selected link is not for an attachment.
41                    return ()
42