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