pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Dirk Zimmermann <dirk@pep-project.org>
Wed, 18 May 2016 08:24:12 +0200
changeset 196 adbb445a7208
parent 155 a32f3ee13848
child 207 77ab2e8e918d
permissions -rw-r--r--
Account creation: Unwind segue back to INBOX
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 Foundation
dirk@30
    10
import UIKit
dirk@31
    11
import CoreData
dirk@30
    12
dirk@58
    13
struct UIState {
dirk@58
    14
    let runningOpsUser = NSMutableOrderedSet()
dirk@58
    15
    let runningOpsAuto = NSMutableOrderedSet()
dirk@58
    16
dirk@58
    17
    func isSynching() -> Bool {
dirk@58
    18
        return runningOpsUser.count > 0 || runningOpsAuto.count > 0
dirk@58
    19
    }
dirk@58
    20
dirk@58
    21
    func isSynchingAuto() -> Bool {
dirk@58
    22
        return runningOpsAuto.count > 0
dirk@58
    23
    }
dirk@58
    24
dirk@58
    25
    func isSynchingUser() -> Bool {
dirk@58
    26
        return runningOpsUser.count > 0
dirk@58
    27
    }
dirk@58
    28
}
dirk@58
    29
dirk@31
    30
class EmailListViewController: UITableViewController {
dirk@155
    31
    let comp = " "
dirk@30
    32
dirk@31
    33
    var appConfig: AppConfig?
dirk@31
    34
    var fetchController: NSFetchedResultsController?
dirk@58
    35
    let state = UIState()
dirk@31
    36
dirk@31
    37
    override func viewWillAppear(animated: Bool) {
dirk@31
    38
        if appConfig == nil {
dirk@31
    39
            if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
dirk@31
    40
                appConfig = appDelegate.appConfig
dirk@31
    41
            }
dirk@31
    42
        }
ana@152
    43
ana@152
    44
        let account:IAccount? = appConfig!.model.fetchLastAccount()
ana@152
    45
        if (account == nil)  {
ana@152
    46
            self.performSegueWithIdentifier("userSettings", sender: self)
ana@152
    47
        }
ana@152
    48
ana@142
    49
        prepareFetchRequest()
dirk@55
    50
dirk@115
    51
        if let account = appConfig?.model.fetchLastAccount() {
dirk@55
    52
            let connectInfo = account.connectInfo
dirk@55
    53
dirk@67
    54
            appConfig!.grandOperator.prefetchEmails(
dirk@55
    55
                connectInfo, folder: ImapSync.defaultImapInboxName, completionBlock: {
dirk@67
    56
                    [unowned self] error in
dirk@58
    57
                    GCD.onMain({
dirk@67
    58
                        Log.info(self.comp, "Sync completed, error: \(error)")
dirk@149
    59
                        self.updateUI()
dirk@58
    60
                    })
dirk@55
    61
            })
dirk@149
    62
            updateUI()
dirk@55
    63
        }
dirk@149
    64
        super.viewWillAppear(animated)
dirk@31
    65
    }
dirk@31
    66
dirk@196
    67
    @IBAction func newAccountCreatedSegue(segue: UIStoryboardSegue) {
dirk@196
    68
    }
dirk@196
    69
ana@143
    70
    func prepareFetchRequest() {
dirk@31
    71
        let predicates: [NSPredicate] = [NSPredicate.init(value: true)]
dirk@31
    72
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
    73
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
    74
            andPredicateWithSubpredicates: predicates)
dirk@119
    75
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate", ascending: false)]
dirk@31
    76
        fetchController = NSFetchedResultsController.init(
dirk@31
    77
            fetchRequest: fetchRequest,
dirk@31
    78
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
    79
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
    80
        fetchController?.delegate = self
dirk@31
    81
        do {
dirk@31
    82
            try fetchController?.performFetch()
dirk@31
    83
        } catch let err as NSError {
dirk@31
    84
            Log.error(comp, error: err)
dirk@31
    85
        }
dirk@31
    86
    }
dirk@31
    87
dirk@58
    88
    // MARK: - UI State
dirk@58
    89
dirk@58
    90
    func updateUI() {
dirk@58
    91
        if state.isSynching() {
dirk@58
    92
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
    93
        } else {
dirk@58
    94
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
    95
        }
dirk@58
    96
    }
dirk@58
    97
dirk@31
    98
    // MARK: - UITableViewDataSource
dirk@31
    99
dirk@31
   100
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@31
   101
        return (fetchController?.sections?.count)!
dirk@31
   102
    }
dirk@31
   103
dirk@31
   104
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   105
        if fetchController?.sections?.count > 0 {
dirk@31
   106
            if let sections = fetchController?.sections {
dirk@31
   107
                let sectionInfo = sections[section]
dirk@31
   108
                return sectionInfo.numberOfObjects
dirk@31
   109
            }
dirk@31
   110
        }
dirk@31
   111
        return 0
dirk@31
   112
    }
dirk@31
   113
dirk@31
   114
    override func tableView(tableView: UITableView,
dirk@31
   115
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@31
   116
        let cell = tableView.dequeueReusableCellWithIdentifier("EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   117
        configureCell(cell, indexPath: indexPath)
dirk@31
   118
        return cell
dirk@31
   119
    }
dirk@31
   120
dirk@31
   121
    func putString(string: String?, toLabel: UILabel) {
dirk@31
   122
        if string?.characters.count > 0 {
dirk@31
   123
            toLabel.hidden = false
dirk@31
   124
            toLabel.text = string!
dirk@31
   125
        } else {
dirk@31
   126
            toLabel.hidden = true
dirk@31
   127
        }
dirk@31
   128
    }
dirk@31
   129
dirk@31
   130
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   131
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@31
   132
            putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@31
   133
            putString(email.subject, toLabel: cell.subjectLabel)
dirk@31
   134
            putString(nil, toLabel: cell.summaryLabel)
dirk@32
   135
dirk@119
   136
            if let originationDate = email.originationDate {
dirk@32
   137
                let formatter = NSDateFormatter.init()
dirk@32
   138
                formatter.dateStyle = .ShortStyle
dirk@32
   139
                formatter.timeStyle = .ShortStyle
dirk@119
   140
                putString(formatter.stringFromDate(originationDate), toLabel: cell.dateLabel)
dirk@32
   141
            } else {
dirk@32
   142
                putString(nil, toLabel: cell.dateLabel)
dirk@32
   143
            }
dirk@31
   144
        }
dirk@30
   145
    }
dirk@30
   146
dirk@30
   147
}
dirk@30
   148
dirk@31
   149
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   150
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   151
        tableView.beginUpdates()
dirk@30
   152
    }
dirk@30
   153
dirk@31
   154
    func controller(controller: NSFetchedResultsController,
dirk@31
   155
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   156
                                     atIndex sectionIndex: Int,
dirk@31
   157
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   158
        switch (type) {
dirk@31
   159
        case .Insert:
dirk@31
   160
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   161
                                     withRowAnimation: .Fade)
dirk@31
   162
        case .Delete:
dirk@31
   163
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   164
                                     withRowAnimation: .Fade)
dirk@31
   165
        default:
dirk@31
   166
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   167
        }
dirk@30
   168
    }
dirk@30
   169
dirk@31
   170
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   171
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   172
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   173
                                              newIndexPath: NSIndexPath?) {
dirk@40
   174
        switch type {
dirk@40
   175
        case .Insert:
dirk@40
   176
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   177
        case .Delete:
dirk@40
   178
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   179
        case .Update:
dirk@40
   180
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   181
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   182
            } else {
dirk@40
   183
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   184
            }
dirk@40
   185
        case .Move:
dirk@40
   186
            if newIndexPath != indexPath {
dirk@40
   187
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   188
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   189
            }
dirk@31
   190
        }
dirk@31
   191
    }
dirk@31
   192
dirk@31
   193
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   194
        tableView.endUpdates()
dirk@31
   195
    }
dirk@30
   196
}