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