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