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