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