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