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