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