pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author buff <andreas@pep-project.org>
Sat, 10 Feb 2018 12:32:24 +0100
branchIOS-140
changeset 3917 37b74989730d
parent 3911 eea974e58b60
child 3951 dc31c89b9aa1
permissions -rw-r--r--
IOS-140 fixes: unified inbox evaluated for archive/delete behaviour instead of msg.parent
dirk@30
     1
//
dirk@30
     2
//  EmailListViewController.swift
dirk@30
     3
//  pEpForiOS
dirk@30
     4
//
dirk@30
     5
//  Created by Dirk Zimmermann on 16/04/16.
dirk@30
     6
//  Copyright © 2016 p≡p Security S.A. All rights reserved.
dirk@30
     7
//
dirk@30
     8
dirk@30
     9
import UIKit
dirk@810
    10
import MessageModel
xavier@3368
    11
import SwipeCellKit
dirk@810
    12
xavier@3368
    13
class EmailListViewController: BaseTableViewController, SwipeTableViewCellDelegate {
andreas@3223
    14
    var folderToShow: Folder?
andreas@3677
    15
andreas@3677
    16
    func updateLastLookAt() {
andreas@3677
    17
        guard let saveFolder = folderToShow else {
andreas@3677
    18
            return
andreas@3677
    19
        }
andreas@3677
    20
        saveFolder.updateLastLookAt()
andreas@3677
    21
    }
andreas@3677
    22
    
andreas@3151
    23
    private var model: EmailListViewModel?
andreas@3677
    24
    
andreas@3151
    25
    private let queue: OperationQueue = {
andreas@3151
    26
        let createe = OperationQueue()
andreas@3151
    27
        createe.qualityOfService = .userInteractive
andreas@3678
    28
        createe.maxConcurrentOperationCount = 5
andreas@3151
    29
        return createe
andreas@3151
    30
    }()
andreas@3151
    31
    private var operations = [IndexPath:Operation]()
andreas@2838
    32
    public static let storyboardId = "EmailListViewController"
andreas@3151
    33
    fileprivate var lastSelectedIndexPath: IndexPath?
andreas@3208
    34
    
igor@1301
    35
    let searchController = UISearchController(searchResultsController: nil)
xavier@3368
    36
xavier@3368
    37
    //swipe acctions types
xavier@3368
    38
    var buttonDisplayMode: ButtonDisplayMode = .titleAndImage
xavier@3368
    39
    var buttonStyle: ButtonStyle = .backgroundColor
andreas@3678
    40
andreas@3678
    41
    /// Indicates that we must not trigger reloadData.
andreas@3678
    42
    private var loadingBlocked = false
andreas@3208
    43
    
andreas@3151
    44
    // MARK: - Outlets
andreas@3208
    45
    
dirk@2067
    46
    @IBOutlet weak var enableFilterButton: UIBarButtonItem!
dirk@2067
    47
    @IBOutlet weak var textFilterButton: UIBarButtonItem!
andreas@3151
    48
    @IBOutlet var showFoldersButton: UIBarButtonItem!
andreas@3677
    49
    
andreas@3151
    50
    // MARK: - Life Cycle
andreas@3208
    51
    
dirk@275
    52
    override func viewDidLoad() {
ylandert@935
    53
        super.viewDidLoad()
dirk@2189
    54
        title = NSLocalizedString("Inbox", comment: "General name for (unified) inbox")
igor@1284
    55
        UIHelper.emailListTableHeight(self.tableView)
andreas@3163
    56
        self.textFilterButton.isEnabled = false
igor@1301
    57
        addSearchBar()
dirk@275
    58
    }
andreas@3208
    59
    
dirk@784
    60
    override func viewWillAppear(_ animated: Bool) {
igor@1301
    61
        super.viewWillAppear(animated)
xavier@2325
    62
        self.navigationController?.setToolbarHidden(false, animated: true)
dirk@1344
    63
        if MiscUtil.isUnitTest() {
dirk@1344
    64
            return
dirk@1344
    65
        }
andreas@3223
    66
dirk@1826
    67
        setDefaultColors()
andreas@3151
    68
        setup()
andreas@3208
    69
        
dirk@2191
    70
        // Mark this folder as having been looked at by the user
andreas@3151
    71
        updateLastLookAt()
andreas@3151
    72
        setupFoldersBarButton()
xavier@3562
    73
        if model != nil {
xavier@3562
    74
            updateFilterButtonView()
xavier@3562
    75
        }
andreas@3151
    76
    }
andreas@3208
    77
    
andreas@3151
    78
    // MARK: - NavigationBar
andreas@3208
    79
    
andreas@3151
    80
    private func hideFoldersNavigationBarButton() {
andreas@3151
    81
        self.showFoldersButton.isEnabled = false
andreas@3151
    82
        self.showFoldersButton.tintColor = UIColor.clear
andreas@3151
    83
    }
andreas@3208
    84
    
andreas@3151
    85
    private func showFoldersNavigationBarButton() {
andreas@3151
    86
        self.showFoldersButton.isEnabled = true
andreas@3151
    87
        self.showFoldersButton.tintColor = nil
andreas@3151
    88
    }
andreas@3208
    89
    
andreas@3151
    90
    private func resetModel() {
andreas@3223
    91
        if folderToShow != nil {
andreas@3291
    92
            model = EmailListViewModel(delegate: self,
andreas@3291
    93
                                       messageSyncService: appConfig.messageSyncService,
andreas@3291
    94
                                       folderToShow: folderToShow)
xavier@2585
    95
        }
dirk@1348
    96
    }
andreas@3208
    97
    
andreas@3151
    98
    private func setup() {
andreas@3289
    99
        if noAccountsExist() {
andreas@3272
   100
            // No account exists. Show account setup.
andreas@3272
   101
            performSegue(withIdentifier:.segueAddNewAccount, sender: self)
andreas@3289
   102
        } else if let vm = model {
andreas@3223
   103
            // We came back from e.g EmailView ...
andreas@3223
   104
            updateFilterText()
andreas@3223
   105
            // ... so we want to update "seen" status
andreas@3226
   106
            vm.reloadData()
andreas@3272
   107
        } else if folderToShow == nil {
andreas@3223
   108
            // We have not been created to show a specific folder, thus we show unified inbox
andreas@3151
   109
            folderToShow = UnifiedInbox()
andreas@3223
   110
            resetModel()
andreas@3272
   111
        } else if model == nil {
andreas@3223
   112
            // We still got no model, because:
andreas@3223
   113
            // - We are not coming back from a pushed view (for instance ComposeEmailView)
andreas@3223
   114
            // - We are not a UnifiedInbox
andreas@3226
   115
            // So we have been created to show a specific folder. Show it!
andreas@3223
   116
            resetModel()
andreas@3151
   117
        }
andreas@3272
   118
andreas@3151
   119
        self.title = realNameOfFolderToShow()
andreas@2683
   120
    }
andreas@3223
   121
andreas@3223
   122
    private func weCameBackFromAPushedView() -> Bool {
andreas@3223
   123
        return model != nil
andreas@3223
   124
    }
andreas@3208
   125
    
andreas@3151
   126
    private func noAccountsExist() -> Bool {
andreas@3151
   127
        return Account.all().isEmpty
igor@1301
   128
    }
andreas@3208
   129
    
andreas@3151
   130
    private func setupFoldersBarButton() {
andreas@3151
   131
        if let size = navigationController?.viewControllers.count, size > 1 {
andreas@3151
   132
            hideFoldersNavigationBarButton()
andreas@3151
   133
        } else {
andreas@3151
   134
            showFoldersNavigationBarButton()
xavier@2132
   135
        }
igor@1338
   136
    }
andreas@3208
   137
    
andreas@3151
   138
    private func addSearchBar() {
igor@1301
   139
        searchController.searchResultsUpdater = self
igor@1301
   140
        searchController.dimsBackgroundDuringPresentation = false
igor@1301
   141
        searchController.delegate = self
igor@1301
   142
        definesPresentationContext = true
igor@1301
   143
        tableView.tableHeaderView = searchController.searchBar
xavier@3209
   144
        tableView.setContentOffset(CGPoint(x: 0.0, y: searchController.searchBar.frame.size.height), animated: false)
igor@1301
   145
    }
andreas@3208
   146
    
andreas@3151
   147
    // MARK: - Other
andreas@3208
   148
    
andreas@3151
   149
    private func realNameOfFolderToShow() -> String? {
andreas@3224
   150
        return folderToShow?.realName
andreas@2697
   151
    }
andreas@3522
   152
andreas@3522
   153
    private func address(forRowAt indexPath: IndexPath) -> String {
andreas@3522
   154
        guard
andreas@3522
   155
            let saveModel = model,
andreas@3522
   156
            let row = saveModel.row(for: indexPath),
andreas@3522
   157
            let folder = folderToShow
andreas@3522
   158
            else {
andreas@3522
   159
                Log.shared.errorAndCrash(component: #function, errorString: "Invalid state")
andreas@3522
   160
                return ""
andreas@3522
   161
        }
andreas@3522
   162
        switch folder.folderType {
andreas@3522
   163
        case .all: fallthrough
andreas@3522
   164
        case .archive: fallthrough
andreas@3522
   165
        case .spam: fallthrough
andreas@3522
   166
        case .trash: fallthrough
andreas@3522
   167
        case .flagged: fallthrough
andreas@3522
   168
        case .inbox: fallthrough
andreas@3522
   169
        case .normal:
andreas@3522
   170
            return row.from
andreas@3522
   171
        case .drafts: fallthrough
andreas@3522
   172
        case .sent:
andreas@3522
   173
            return row.to
andreas@3522
   174
        }
andreas@3522
   175
    }
andreas@3522
   176
andreas@3522
   177
    private func shouldShowAccessoryDisclosureIndicator() -> Bool {
andreas@3522
   178
        guard let folder = folderToShow else {
andreas@3522
   179
            Log.shared.errorAndCrash(component: #function, errorString: "No folder")
andreas@3522
   180
            return true
andreas@3522
   181
        }
andreas@3522
   182
        if folder.folderType == .drafts {
andreas@3522
   183
            // Mails in drafts folder can only be opened in compose mode, which is shown modally.
andreas@3522
   184
            return false
andreas@3522
   185
        }
andreas@3522
   186
        return true
andreas@3522
   187
    }
andreas@3208
   188
    
andreas@3151
   189
    private func configure(cell: EmailListViewCell, for indexPath: IndexPath) {
andreas@3677
   190
        // Configure lightweight stuff on main thread ...
andreas@3677
   191
        guard let saveModel = model else {
andreas@3151
   192
            return
xavier@2967
   193
        }
andreas@3151
   194
        guard let row = saveModel.row(for: indexPath) else {
andreas@3151
   195
            Log.shared.errorAndCrash(component: #function, errorString: "We should have a row here")
andreas@3151
   196
            return
andreas@3151
   197
        }
andreas@3522
   198
        // Mails in drafts folder can only be opened in compose mode, which is shown modally.
andreas@3522
   199
        cell.accessoryDisclosureIndicator.isHidden = shouldShowAccessoryDisclosureIndicator()
andreas@3522
   200
        cell.addressLabel.text = address(forRowAt: indexPath)
andreas@3151
   201
        cell.subjectLabel.text = row.subject
andreas@3151
   202
        cell.summaryLabel.text = row.bodyPeek
andreas@3151
   203
        cell.isFlagged = row.isFlagged
andreas@3151
   204
        cell.isSeen = row.isSeen
andreas@3151
   205
        cell.hasAttachment = row.showAttchmentIcon
andreas@3151
   206
        cell.dateLabel.text = row.dateText
andreas@3151
   207
        // Set image from cache if any
andreas@3151
   208
        cell.setContactImage(image: row.senderContactImage)
andreas@3521
   209
andreas@3151
   210
        let op = BlockOperation() { [weak self] in
andreas@3419
   211
            MessageModel.performAndWait {
andreas@3419
   212
                // ... and expensive computations in background
andreas@3419
   213
                guard let strongSelf = self else {
andreas@3419
   214
                    // View is gone, nothing to do.
andreas@3419
   215
                    return
andreas@3419
   216
                }
andreas@3419
   217
                
andreas@3419
   218
                var senderImage: UIImage?
andreas@3419
   219
                if row.senderContactImage == nil {
andreas@3419
   220
                    // image for identity has not been cached yet
andreas@3522
   221
                    // Get (and cache) it here in the background ...
andreas@3419
   222
                    senderImage = strongSelf.model?.senderImage(forCellAt: indexPath)
andreas@3419
   223
                    
andreas@3419
   224
                    // ... and set it on the main queue
andreas@3419
   225
                    DispatchQueue.main.async {
andreas@3419
   226
                        if senderImage != nil && senderImage != cell.contactImageView.image {
andreas@3419
   227
                            cell.contactImageView.image  = senderImage
andreas@3419
   228
                        }
andreas@3220
   229
                    }
andreas@3220
   230
                }
andreas@3419
   231
                
andreas@3419
   232
                let pEpRatingImage = strongSelf.model?.pEpRatingColorImage(forCellAt: indexPath)
andreas@3419
   233
                
andreas@3419
   234
                // In theory we want to set all data in *one* async call. But as pEpRatingColorImage takes
andreas@3419
   235
                // very long, we are setting the sender image seperatelly.
andreas@3419
   236
                DispatchQueue.main.async {
andreas@3419
   237
                    if pEpRatingImage != nil {
andreas@3419
   238
                        cell.setPepRatingImage(image: pEpRatingImage)
andreas@3419
   239
                    }
andreas@3151
   240
                }
andreas@3151
   241
            }
andreas@3151
   242
        }
andreas@3151
   243
        queue(operation: op, for: indexPath)
xavier@2967
   244
    }
andreas@3505
   245
andreas@3505
   246
    private func showComposeView() {
andreas@3505
   247
        self.performSegue(withIdentifier: SegueIdentifier.segueEditDraft, sender: self)
andreas@3505
   248
    }
andreas@3505
   249
andreas@3505
   250
    private func showEmail(forCellAt indexPath: IndexPath) {
andreas@3505
   251
        performSegue(withIdentifier: SegueIdentifier.segueShowEmail, sender: self)
andreas@3505
   252
        guard let vm = model else {
andreas@3505
   253
            Log.shared.errorAndCrash(component: #function, errorString: "No model.")
andreas@3505
   254
            return
andreas@3505
   255
        }
andreas@3505
   256
        vm.markRead(forIndexPath: indexPath)
andreas@3505
   257
    }
andreas@3208
   258
    
andreas@3678
   259
    // MARK: - Action Filter Button
andreas@3208
   260
    
andreas@3151
   261
    @IBAction func filterButtonHasBeenPressed(_ sender: UIBarButtonItem) {
andreas@3678
   262
        guard !loadingBlocked else {
andreas@3678
   263
            return
andreas@3678
   264
        }
andreas@3163
   265
        guard let vm = model else {
andreas@3163
   266
            Log.shared.errorAndCrash(component: #function, errorString: "We should have a model here")
andreas@3163
   267
            return
andreas@3163
   268
        }
andreas@3678
   269
        stopLoading()
andreas@3163
   270
        vm.isFilterEnabled = !vm.isFilterEnabled
xavier@3193
   271
        updateFilterButtonView()
xavier@1832
   272
    }
andreas@3208
   273
    
andreas@3678
   274
    private func updateFilterButtonView() {
andreas@3163
   275
        guard let vm = model else {
andreas@3163
   276
            Log.shared.errorAndCrash(component: #function, errorString: "We should have a model here")
andreas@3163
   277
            return
andreas@3163
   278
        }
andreas@3208
   279
        
andreas@3163
   280
        textFilterButton.isEnabled = vm.isFilterEnabled
andreas@3163
   281
        if textFilterButton.isEnabled {
andreas@3163
   282
            enableFilterButton.image = UIImage(named: "unread-icon-active")
andreas@3163
   283
            updateFilterText()
andreas@3163
   284
        } else {
andreas@3163
   285
            textFilterButton.title = ""
andreas@3163
   286
            enableFilterButton.image = UIImage(named: "unread-icon")
andreas@3163
   287
        }
andreas@3163
   288
    }
andreas@3208
   289
    
andreas@3678
   290
    private func updateFilterText() {
xavier@3193
   291
        if let vm = model, let txt = vm.activeFilter?.title {
andreas@3163
   292
            textFilterButton.title = "Filter by: " + txt
andreas@3163
   293
        }
andreas@3151
   294
    }
andreas@3208
   295
    
dirk@31
   296
    // MARK: - UITableViewDataSource
andreas@3208
   297
    
dirk@784
   298
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
andreas@3151
   299
        return model?.rowCount ?? 0
dirk@31
   300
    }
andreas@3208
   301
    
dirk@784
   302
    override func tableView(_ tableView: UITableView,
dirk@784
   303
                            cellForRowAt indexPath: IndexPath) -> UITableViewCell {
andreas@3151
   304
        guard let cell = tableView.dequeueReusableCell(withIdentifier: EmailListViewCell.storyboardId,
andreas@3151
   305
                                                       for: indexPath) as? EmailListViewCell
andreas@3151
   306
            else {
andreas@3151
   307
                Log.shared.errorAndCrash(component: #function, errorString: "Wrong cell!")
andreas@3151
   308
                return UITableViewCell()
andreas@3151
   309
        }
xavier@3368
   310
        cell.delegate = self
andreas@3151
   311
        configure(cell: cell, for: indexPath)
dirk@31
   312
        return cell
dirk@31
   313
    }
andreas@3208
   314
    
andreas@3513
   315
    // MARK: - SwipeTableViewCellDelegate
xavier@3368
   316
andreas@3911
   317
    func tableView(_ tableView: UITableView,
andreas@3911
   318
                   editActionsForRowAt
andreas@3911
   319
        indexPath: IndexPath,
andreas@3911
   320
                   for orientation: SwipeActionsOrientation) -> [SwipeAction]? {
andreas@3917
   321
andreas@3909
   322
        // Create swipe actions, taking the currently displayed folder into account
andreas@3514
   323
        var swipeActions = [SwipeAction]()
andreas@3911
   324
andreas@3917
   325
        // Get messages parent folder
andreas@3917
   326
        let parentFolder: Folder
andreas@3917
   327
        if let folder = folderToShow, !(folder is UnifiedInbox) {
andreas@3917
   328
            // Do not bother our imperformant MessageModel if we already know the parent folder
andreas@3917
   329
            parentFolder = folder
andreas@3917
   330
        } else {
andreas@3917
   331
            // folderToShow is unified inbox, fetch parent folder from DB.
andreas@3917
   332
            guard let vm = model,
andreas@3917
   333
                let folder = vm.message(representedByRowAt: indexPath)?.parent else {
andreas@3917
   334
                    Log.shared.errorAndCrash(component: #function, errorString: "Dangling Message")
andreas@3917
   335
                    return nil
andreas@3917
   336
            }
andreas@3917
   337
            parentFolder = folder
andreas@3917
   338
        }
andreas@3917
   339
andreas@3911
   340
        // Delete or Archive
andreas@3917
   341
        let defaultIsArchive = parentFolder.defaultDestructiveActionIsArchive
andreas@3917
   342
        let titleDestructive = defaultIsArchive ? "Archive" : "Delete"
andreas@3917
   343
        let descriptorDestructive: ActionDescriptor = defaultIsArchive ? .archive : .trash
andreas@3911
   344
        let archiveAction =
andreas@3911
   345
            SwipeAction(style: .destructive, title: titleDestructive) {action, indexPath in
andreas@3909
   346
                self.deleteAction(forCellAt: indexPath)
andreas@3514
   347
        }
andreas@3911
   348
        configure(action: archiveAction, with: descriptorDestructive)
andreas@3911
   349
        swipeActions.append(archiveAction)
andreas@3514
   350
andreas@3909
   351
        // Flag
andreas@3514
   352
        let flagAction = SwipeAction(style: .default, title: "Flag") { action, indexPath in
andreas@3514
   353
            self.flagAction(forCellAt: indexPath)
andreas@3514
   354
        }
andreas@3514
   355
        flagAction.hidesWhenSelected = true
andreas@3514
   356
        configure(action: flagAction, with: .flag)
andreas@3514
   357
        swipeActions.append(flagAction)
andreas@3514
   358
andreas@3909
   359
        // More (reply++)
andreas@3917
   360
        if parentFolder.folderType != .drafts {
andreas@3514
   361
            // Do not add "more" actions (reply...) to drafted mails.
andreas@3514
   362
            let moreAction = SwipeAction(style: .default, title: "More") { action, indexPath in
andreas@3514
   363
                self.moreAction(forCellAt: indexPath)
xavier@3368
   364
            }
andreas@3514
   365
            moreAction.hidesWhenSelected = true
andreas@3514
   366
            configure(action: moreAction, with: .more)
andreas@3514
   367
            swipeActions.append(moreAction)
xavier@3368
   368
        }
andreas@3514
   369
        return (orientation == .right ?   swipeActions : nil)
xavier@3368
   370
    }
xavier@3368
   371
xavier@3368
   372
    func tableView(_ tableView: UITableView, editActionsOptionsForRowAt indexPath: IndexPath, for orientation: SwipeActionsOrientation) -> SwipeTableOptions {
xavier@3368
   373
        var options = SwipeTableOptions()
xavier@3368
   374
        options.expansionStyle = .destructive
xavier@3368
   375
        options.transitionStyle = .border
xavier@3368
   376
        options.buttonSpacing = 11
xavier@3368
   377
        return options
xavier@3368
   378
    }
xavier@3368
   379
xavier@3368
   380
    func configure(action: SwipeAction, with descriptor: ActionDescriptor) {
xavier@3368
   381
        action.title = descriptor.title(forDisplayMode: buttonDisplayMode)
xavier@3368
   382
        action.image = descriptor.image(forStyle: buttonStyle, displayMode: buttonDisplayMode)
xavier@3368
   383
xavier@3368
   384
        switch buttonStyle {
xavier@3368
   385
        case .backgroundColor:
xavier@3368
   386
            action.backgroundColor = descriptor.color
xavier@3368
   387
        case .circular:
xavier@3368
   388
            action.backgroundColor = .clear
xavier@3368
   389
            action.textColor = descriptor.color
xavier@3368
   390
            action.font = .systemFont(ofSize: 13)
xavier@3368
   391
            action.transitionDelegate = ScaleTransition.default
xavier@3368
   392
        }
xavier@3368
   393
    }
andreas@3208
   394
    
andreas@3151
   395
    override func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
andreas@3151
   396
        cancelOperation(for: indexPath)
dirk@744
   397
    }
andreas@3208
   398
    
andreas@3151
   399
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
andreas@3505
   400
        guard let folder = folderToShow else {
andreas@3505
   401
            Log.shared.errorAndCrash(component: #function, errorString: "No folder")
andreas@3505
   402
            return
andreas@3505
   403
        }
andreas@3151
   404
        lastSelectedIndexPath = indexPath
andreas@3151
   405
        tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
andreas@3505
   406
andreas@3505
   407
        if folder.folderType == .drafts {
andreas@3505
   408
            showComposeView()
andreas@3505
   409
        } else {
andreas@3505
   410
            showEmail(forCellAt: indexPath)
andreas@3425
   411
        }
dirk@744
   412
    }
andreas@3278
   413
andreas@3291
   414
    // Implemented to get informed about the scrolling position.
andreas@3291
   415
    // If the user has scrolled down (almost) to the end, we need to get older emails to display.
andreas@3291
   416
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell,
andreas@3291
   417
                            forRowAt indexPath: IndexPath) {
andreas@3278
   418
        guard let vm = model else {
andreas@3291
   419
            Log.shared.errorAndCrash(component: #function, errorString: "No model.")
andreas@3291
   420
            return
andreas@3278
   421
        }
andreas@3291
   422
        vm.fetchOlderMessagesIfRequired(forIndexPath: indexPath)
andreas@3278
   423
    }
andreas@3278
   424
andreas@3151
   425
    // MARK: - Queue Handling
andreas@3678
   426
andreas@3678
   427
    /// Cancels all operations and sets tableView.dataSource to nil.
andreas@3678
   428
    /// Used to avoid that an operation accesses an outdated view model
andreas@3678
   429
    private func stopLoading() {
andreas@3678
   430
        loadingBlocked = true
andreas@3678
   431
        tableView.dataSource = nil
andreas@3678
   432
        queue.cancelAllOperations()
andreas@3678
   433
        queue.waitUntilAllOperationsAreFinished()
andreas@3678
   434
    }
andreas@3208
   435
    
andreas@3151
   436
    private func queue(operation op:Operation, for indexPath: IndexPath) {
andreas@3151
   437
        operations[indexPath] = op
andreas@3151
   438
        queue.addOperation(op)
dirk@1507
   439
    }
andreas@3208
   440
    
andreas@3151
   441
    private func cancelOperation(for indexPath:IndexPath) {
andreas@3151
   442
        guard let op = operations.removeValue(forKey: indexPath) else {
andreas@3151
   443
            return
dirk@744
   444
        }
andreas@3151
   445
        if !op.isCancelled  {
andreas@3151
   446
            op.cancel()
dirk@1507
   447
        }
dirk@744
   448
    }
andreas@3291
   449
andreas@3291
   450
    // MARK: -
andreas@3291
   451
andreas@3151
   452
    override func didReceiveMemoryWarning() {
andreas@3151
   453
        model?.freeMemory()
andreas@3151
   454
    }
andreas@3151
   455
}
andreas@3151
   456
andreas@3151
   457
// MARK: - UISearchResultsUpdating, UISearchControllerDelegate
andreas@3151
   458
andreas@3151
   459
extension EmailListViewController: UISearchResultsUpdating, UISearchControllerDelegate {
andreas@3151
   460
    public func updateSearchResults(for searchController: UISearchController) {
andreas@3151
   461
        guard let vm = model, let searchText = searchController.searchBar.text else {
andreas@3151
   462
            return
igor@1242
   463
        }
andreas@3163
   464
        vm.setSearchFilter(forSearchText: searchText)
igor@1242
   465
    }
andreas@3208
   466
    
andreas@3151
   467
    func didDismissSearchController(_ searchController: UISearchController) {
andreas@3151
   468
        guard let vm = model else {
andreas@3151
   469
            return
andreas@3151
   470
        }
andreas@3151
   471
        vm.removeSearchFilter()
andreas@3151
   472
    }
andreas@3151
   473
}
xavier@1623
   474
andreas@3151
   475
// MARK: - EmailListModelDelegate
andreas@3151
   476
andreas@3151
   477
extension EmailListViewController: EmailListViewModelDelegate {
andreas@3151
   478
    func emailListViewModel(viewModel: EmailListViewModel, didInsertDataAt indexPath: IndexPath) {
dirk@3866
   479
        Log.shared.info(component: #function, content: "\(model?.rowCount ?? 0)")
andreas@3166
   480
        tableView.beginUpdates()
andreas@3151
   481
        tableView.insertRows(at: [indexPath], with: .automatic)
andreas@3151
   482
        tableView.endUpdates()
andreas@3151
   483
    }
andreas@3208
   484
    
andreas@3151
   485
    func emailListViewModel(viewModel: EmailListViewModel, didRemoveDataAt indexPath: IndexPath) {
dirk@3866
   486
        Log.shared.info(component: #function, content: "\(model?.rowCount ?? 0)")
andreas@3151
   487
        tableView.beginUpdates()
andreas@3151
   488
        tableView.deleteRows(at: [indexPath], with: .automatic)
andreas@3151
   489
        tableView.endUpdates()
andreas@3151
   490
    }
andreas@3208
   491
    
andreas@3151
   492
    func emailListViewModel(viewModel: EmailListViewModel, didUpdateDataAt indexPath: IndexPath) {
dirk@3866
   493
        Log.shared.info(component: #function, content: "\(model?.rowCount ?? 0)")
andreas@3151
   494
        tableView.beginUpdates()
andreas@3151
   495
        tableView.reloadRows(at: [indexPath], with: .none)
andreas@3151
   496
        tableView.endUpdates()
andreas@3151
   497
    }
andreas@3677
   498
    
andreas@3677
   499
    func updateView() {
andreas@3678
   500
        loadingBlocked = false
andreas@3678
   501
        tableView.dataSource = self
andreas@3678
   502
        tableView.reloadData()
andreas@3151
   503
    }
andreas@3151
   504
}
andreas@3151
   505
andreas@3151
   506
// MARK: - ActionSheet & ActionSheet Actions
andreas@3151
   507
andreas@3151
   508
extension EmailListViewController {
andreas@3166
   509
    func showMoreActionSheet(forRowAt indexPath: IndexPath) {
andreas@3151
   510
        lastSelectedIndexPath = indexPath
igor@1242
   511
        let alertControler = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
igor@1438
   512
        alertControler.view.tintColor = .pEpGreen
igor@1242
   513
        let cancelAction = createCancelAction()
andreas@3151
   514
        let replyAction = createReplyAction()
andreas@3151
   515
        let replyAllAction = createReplyAllAction()
andreas@3151
   516
        let forwardAction = createForwardAction()
igor@1242
   517
        alertControler.addAction(cancelAction)
igor@1242
   518
        alertControler.addAction(replyAction)
xavier@1620
   519
        alertControler.addAction(replyAllAction)
igor@1242
   520
        alertControler.addAction(forwardAction)
igor@1414
   521
        if let popoverPresentationController = alertControler.popoverPresentationController {
andreas@3151
   522
            popoverPresentationController.sourceView = tableView
igor@1414
   523
        }
igor@1242
   524
        present(alertControler, animated: true, completion: nil)
igor@1242
   525
    }
andreas@3208
   526
    
andreas@3151
   527
    // MARK: Action Sheet Actions
andreas@3208
   528
    
igor@1242
   529
    func createCancelAction() -> UIAlertAction {
andreas@3151
   530
        return  UIAlertAction(title: "Cancel", style: .cancel) { (action) in
andreas@3151
   531
            self.tableView.beginUpdates()
andreas@3151
   532
            self.tableView.setEditing(false, animated: true)
andreas@3151
   533
            self.tableView.endUpdates()
igor@1242
   534
        }
igor@1242
   535
    }
andreas@3208
   536
    
andreas@3151
   537
    func createReplyAction() ->  UIAlertAction {
andreas@3151
   538
        return UIAlertAction(title: "Reply", style: .default) { (action) in
andreas@3151
   539
            self.performSegue(withIdentifier: .segueReply, sender: self)
xavier@1620
   540
        }
xavier@1620
   541
    }
andreas@3208
   542
    
andreas@3151
   543
    func createReplyAllAction() ->  UIAlertAction {
andreas@3151
   544
        return UIAlertAction(title: "Reply All", style: .default) { (action) in
andreas@3151
   545
            self.performSegue(withIdentifier: .segueReplyAll, sender: self)
igor@1242
   546
        }
igor@1242
   547
    }
andreas@3208
   548
    
andreas@3151
   549
    func createForwardAction() -> UIAlertAction {
andreas@3151
   550
        return UIAlertAction(title: "Forward", style: .default) { (action) in
andreas@3151
   551
            self.performSegue(withIdentifier: .segueForward, sender: self)
xavier@2369
   552
        }
igor@1301
   553
    }
igor@1301
   554
}
igor@1338
   555
andreas@3151
   556
// MARK: - TableViewCell Actions
andreas@3151
   557
andreas@3151
   558
extension EmailListViewController {
andreas@3151
   559
    private func createRowAction(image: UIImage?,
xavier@3266
   560
                                 action: @escaping (UITableViewRowAction, IndexPath) -> Void
xavier@3266
   561
        ) -> UITableViewRowAction {
xavier@3266
   562
        let rowAction = UITableViewRowAction(style: .normal, title: nil, handler: action)
andreas@3151
   563
        if let theImage = image {
andreas@3151
   564
            let iconColor = UIColor(patternImage: theImage)
andreas@3151
   565
            rowAction.backgroundColor = iconColor
andreas@3151
   566
        }
andreas@3151
   567
        return rowAction
andreas@3151
   568
    }
andreas@3208
   569
    
xavier@3369
   570
    func flagAction(forCellAt indexPath: IndexPath) {
andreas@3151
   571
        guard let row = model?.row(for: indexPath) else {
andreas@3151
   572
            Log.shared.errorAndCrash(component: #function, errorString: "No data for indexPath!")
xavier@3369
   573
            return
andreas@3151
   574
        }
xavier@3369
   575
        if row.isFlagged {
xavier@3369
   576
            model?.unsetFlagged(forIndexPath: indexPath)
xavier@3369
   577
        } else {
xavier@3369
   578
            model?.setFlagged(forIndexPath: indexPath)
andreas@3151
   579
        }
xavier@3369
   580
        tableView.beginUpdates()
xavier@3369
   581
        tableView.setEditing(false, animated: true)
xavier@3369
   582
        tableView.reloadRows(at: [indexPath], with: .none)
xavier@3369
   583
        tableView.endUpdates()
andreas@3151
   584
    }
andreas@3208
   585
    
xavier@3369
   586
    func deleteAction(forCellAt indexPath: IndexPath) {
andreas@3911
   587
        model?.delete(forIndexPath: indexPath)
andreas@3151
   588
    }
andreas@3208
   589
    
xavier@3369
   590
    func moreAction(forCellAt indexPath: IndexPath) {
xavier@3369
   591
        self.showMoreActionSheet(forRowAt: indexPath)
andreas@3151
   592
    }
andreas@3151
   593
}
andreas@3151
   594
andreas@3151
   595
// MARK: - SegueHandlerType
igor@1338
   596
igor@1338
   597
extension EmailListViewController: SegueHandlerType {
andreas@3208
   598
    
igor@1338
   599
    enum SegueIdentifier: String {
igor@1338
   600
        case segueAddNewAccount
igor@1338
   601
        case segueShowEmail
igor@1338
   602
        case segueCompose
xavier@2715
   603
        case segueReply
xavier@1623
   604
        case segueReplyAll
xavier@1664
   605
        case segueForward
andreas@3505
   606
        case segueEditDraft
xavier@1865
   607
        case segueFilter
xavier@2248
   608
        case segueFolderViews
igor@1338
   609
        case noSegue
igor@1338
   610
    }
andreas@3208
   611
    
igor@1338
   612
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
andreas@3505
   613
        let segueId = segueIdentifier(for: segue)
andreas@3505
   614
        switch segueId {
andreas@3505
   615
        case .segueReply,
andreas@3505
   616
             .segueReplyAll,
andreas@3505
   617
             .segueForward,
andreas@3505
   618
             .segueCompose,
andreas@3505
   619
             .segueEditDraft:
andreas@3505
   620
            setupComposeViewController(for: segue)
andreas@3111
   621
        case .segueShowEmail:
andreas@2850
   622
            guard let vc = segue.destination as? EmailViewController,
andreas@3151
   623
                let indexPath = lastSelectedIndexPath,
andreas@3208
   624
                let message = model?.message(representedByRowAt: indexPath) else {
andreas@2850
   625
                    Log.shared.errorAndCrash(component: #function, errorString: "Segue issue")
andreas@2850
   626
                    return
igor@1338
   627
            }
andreas@2850
   628
            vc.appConfig = appConfig
andreas@3151
   629
            vc.message = message
andreas@3223
   630
            vc.folderShow = folderToShow
andreas@3166
   631
            vc.messageId = indexPath.row //that looks wrong
andreas@2850
   632
        case .segueFilter:
andreas@2850
   633
            guard let destiny = segue.destination as? FilterTableViewController  else {
andreas@2850
   634
                Log.shared.errorAndCrash(component: #function, errorString: "Segue issue")
andreas@2850
   635
                return
andreas@2850
   636
            }
andreas@2850
   637
            destiny.appConfig = appConfig
andreas@3163
   638
            destiny.filterDelegate = model
andreas@2850
   639
            destiny.inFolder = false
andreas@3223
   640
            destiny.filterEnabled = folderToShow?.filter
andreas@2850
   641
            destiny.hidesBottomBarWhenPushed = true
andreas@2850
   642
        case .segueAddNewAccount:
andreas@2850
   643
            guard let vc = segue.destination as? LoginTableViewController  else {
andreas@2850
   644
                Log.shared.errorAndCrash(component: #function, errorString: "Segue issue")
andreas@2850
   645
                return
andreas@2850
   646
            }
andreas@2850
   647
            vc.appConfig = appConfig
andreas@2850
   648
            vc.hidesBottomBarWhenPushed = true
xavier@1664
   649
            break
andreas@2850
   650
        case .segueFolderViews:
andreas@2850
   651
            guard let vC = segue.destination as? FolderTableViewController  else {
andreas@2850
   652
                Log.shared.errorAndCrash(component: #function, errorString: "Segue issue")
andreas@2850
   653
                return
xavier@1865
   654
            }
andreas@2850
   655
            vC.appConfig = appConfig
andreas@2850
   656
            vC.hidesBottomBarWhenPushed = true
xavier@1865
   657
            break
andreas@2850
   658
        default:
andreas@2850
   659
            Log.shared.errorAndCrash(component: #function, errorString: "Unhandled segue")
dirk@1694
   660
            break
igor@1338
   661
        }
andreas@2838
   662
    }
andreas@3208
   663
    
andreas@3166
   664
    @IBAction func segueUnwindAccountAdded(segue: UIStoryboardSegue) {
andreas@3151
   665
        // nothing to do.
andreas@3150
   666
    }
andreas@3505
   667
andreas@3505
   668
    private func setupComposeViewController(for segue: UIStoryboardSegue) {
andreas@3505
   669
        let segueId = segueIdentifier(for: segue)
andreas@3505
   670
        guard
andreas@3505
   671
            let nav = segue.destination as? UINavigationController,
andreas@3505
   672
            let composeVc = nav.topViewController as? ComposeTableViewController,
andreas@3505
   673
            let composeMode = composeMode(for: segueId) else {
andreas@3505
   674
                Log.shared.errorAndCrash(component: #function,
andreas@3505
   675
                                         errorString: "composeViewController setup issue")
andreas@3505
   676
                return
andreas@3505
   677
        }
andreas@3505
   678
        composeVc.appConfig = appConfig
andreas@3505
   679
        composeVc.composeMode = composeMode
andreas@3505
   680
        composeVc.origin = folderToShow?.account.user
andreas@3505
   681
        if composeMode != .normal {
andreas@3505
   682
            // This is not a simple compose (but reply, forward or such),
andreas@3505
   683
            // thus we have to pass the original meaasge.
andreas@3505
   684
            guard
andreas@3505
   685
                let indexPath = lastSelectedIndexPath,
andreas@3505
   686
                let message = model?.message(representedByRowAt: indexPath) else {
andreas@3505
   687
                    Log.shared.errorAndCrash(component: #function,
andreas@3505
   688
                                             errorString: "No original message")
andreas@3505
   689
                    return
andreas@3505
   690
            }
andreas@3505
   691
            composeVc.originalMessage = message
andreas@3505
   692
        }
andreas@3505
   693
    }
andreas@3505
   694
andreas@3505
   695
    private func composeMode(for segueId: SegueIdentifier) -> ComposeTableViewController.ComposeMode? {
andreas@3505
   696
        switch segueId {
andreas@3505
   697
        case .segueReply:
andreas@3505
   698
            return .replyFrom
andreas@3505
   699
        case .segueReplyAll:
andreas@3505
   700
            return .replyAll
andreas@3505
   701
        case .segueForward:
andreas@3505
   702
            return .forward
andreas@3505
   703
        case .segueCompose:
andreas@3505
   704
            return .normal
andreas@3505
   705
        case .segueEditDraft:
andreas@3505
   706
            return .draft
andreas@3505
   707
        default:
andreas@3505
   708
            return nil
andreas@3505
   709
        }
andreas@3505
   710
    }
dirk@1348
   711
}
xavier@3368
   712
xavier@3368
   713
//enums to simplify configurations
xavier@3368
   714
xavier@3368
   715
enum ActionDescriptor {
andreas@3909
   716
    case read, more, flag, trash, archive
xavier@3368
   717
xavier@3368
   718
    func title(forDisplayMode displayMode: ButtonDisplayMode) -> String? {
xavier@3368
   719
        guard displayMode != .imageOnly else { return nil }
xavier@3368
   720
xavier@3368
   721
        switch self {
andreas@3909
   722
        case .read: return NSLocalizedString("Read", comment: "read button in slidw left menu")
andreas@3909
   723
        case .more: return NSLocalizedString("More", comment: "more button in slidw left menu")
andreas@3909
   724
        case .flag: return NSLocalizedString("Flag", comment: "read button in slidw left menu")
andreas@3909
   725
        case .trash: return NSLocalizedString("Trash", comment: "Trash button in slidw left menu")
andreas@3909
   726
        case .archive: return NSLocalizedString("Archive", comment: "Archive button in slidw left menu")
xavier@3368
   727
        }
xavier@3368
   728
    }
xavier@3368
   729
xavier@3368
   730
    func image(forStyle style: ButtonStyle, displayMode: ButtonDisplayMode) -> UIImage? {
xavier@3368
   731
        guard displayMode != .titleOnly else { return nil }
xavier@3368
   732
xavier@3368
   733
        let name: String
xavier@3368
   734
        switch self {
xavier@3368
   735
        case .read: name = "read"
xavier@3368
   736
        case .more: name = "more"
xavier@3368
   737
        case .flag: name = "flag"
xavier@3368
   738
        case .trash: name = "trash"
andreas@3909
   739
        case .archive: name = "trash"
xavier@3368
   740
        }
xavier@3368
   741
xavier@3368
   742
        return UIImage(named: "swipe-" + name)
xavier@3368
   743
    }
xavier@3368
   744
xavier@3368
   745
    var color: UIColor {
xavier@3368
   746
        switch self {
xavier@3368
   747
        case .read: return #colorLiteral(red: 0.2980392157, green: 0.8509803922, blue: 0.3921568627, alpha: 1)
xavier@3368
   748
        case .more: return #colorLiteral(red: 0.7803494334, green: 0.7761332393, blue: 0.7967314124, alpha: 1)
xavier@3368
   749
        case .flag: return #colorLiteral(red: 1, green: 0.5803921569, blue: 0, alpha: 1)
xavier@3368
   750
        case .trash: return #colorLiteral(red: 1, green: 0.2352941176, blue: 0.1882352941, alpha: 1)
andreas@3909
   751
        case .archive: return #colorLiteral(red: 0.2980392157, green: 0.8509803922, blue: 0.3921568627, alpha: 1)
xavier@3368
   752
        }
xavier@3368
   753
    }
xavier@3368
   754
}
xavier@3368
   755
xavier@3368
   756
enum ButtonDisplayMode {
xavier@3368
   757
    case titleAndImage, titleOnly, imageOnly
xavier@3368
   758
}
xavier@3368
   759
xavier@3368
   760
enum ButtonStyle {
xavier@3368
   761
    case backgroundColor, circular
xavier@3368
   762
}