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