pEpForiOS/UI/EmailDisplay/EmailListViewController.swift
author Ana Rebollo <ana@pep-project.org>
Mon, 09 May 2016 16:50:52 +0200
changeset 152 356806f5e175
parent 149 4f8e228e77cd
child 155 a32f3ee13848
permissions -rw-r--r--
merge
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@31
    31
    let comp = "EmailListViewController"
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
ana@143
    67
    func prepareFetchRequest() {
dirk@31
    68
        let predicates: [NSPredicate] = [NSPredicate.init(value: true)]
dirk@31
    69
        let fetchRequest = NSFetchRequest.init(entityName: Message.entityName())
dirk@31
    70
        fetchRequest.predicate = NSCompoundPredicate.init(
dirk@31
    71
            andPredicateWithSubpredicates: predicates)
dirk@119
    72
        fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "originationDate", ascending: false)]
dirk@31
    73
        fetchController = NSFetchedResultsController.init(
dirk@31
    74
            fetchRequest: fetchRequest,
dirk@31
    75
            managedObjectContext: appConfig!.coreDataUtil.managedObjectContext,
dirk@31
    76
            sectionNameKeyPath: nil, cacheName: nil)
dirk@31
    77
        fetchController?.delegate = self
dirk@31
    78
        do {
dirk@31
    79
            try fetchController?.performFetch()
dirk@31
    80
        } catch let err as NSError {
dirk@31
    81
            Log.error(comp, error: err)
dirk@31
    82
        }
dirk@31
    83
    }
dirk@31
    84
dirk@58
    85
    // MARK: - UI State
dirk@58
    86
dirk@58
    87
    func updateUI() {
dirk@58
    88
        if state.isSynching() {
dirk@58
    89
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
dirk@58
    90
        } else {
dirk@58
    91
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
dirk@58
    92
        }
dirk@58
    93
    }
dirk@58
    94
dirk@31
    95
    // MARK: - UITableViewDataSource
dirk@31
    96
dirk@31
    97
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
dirk@31
    98
        return (fetchController?.sections?.count)!
dirk@31
    99
    }
dirk@31
   100
dirk@31
   101
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
dirk@31
   102
        if fetchController?.sections?.count > 0 {
dirk@31
   103
            if let sections = fetchController?.sections {
dirk@31
   104
                let sectionInfo = sections[section]
dirk@31
   105
                return sectionInfo.numberOfObjects
dirk@31
   106
            }
dirk@31
   107
        }
dirk@31
   108
        return 0
dirk@31
   109
    }
dirk@31
   110
dirk@31
   111
    override func tableView(tableView: UITableView,
dirk@31
   112
                            cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
dirk@31
   113
        let cell = tableView.dequeueReusableCellWithIdentifier("EmailListViewCell", forIndexPath: indexPath) as! EmailListViewCell
dirk@31
   114
        configureCell(cell, indexPath: indexPath)
dirk@31
   115
        return cell
dirk@31
   116
    }
dirk@31
   117
dirk@31
   118
    func putString(string: String?, toLabel: UILabel) {
dirk@31
   119
        if string?.characters.count > 0 {
dirk@31
   120
            toLabel.hidden = false
dirk@31
   121
            toLabel.text = string!
dirk@31
   122
        } else {
dirk@31
   123
            toLabel.hidden = true
dirk@31
   124
        }
dirk@31
   125
    }
dirk@31
   126
dirk@31
   127
    func configureCell(cell: EmailListViewCell, indexPath: NSIndexPath) {
dirk@31
   128
        if let email = fetchController?.objectAtIndexPath(indexPath) as? Message {
dirk@31
   129
            putString(email.from?.displayString(), toLabel: cell.senderLabel)
dirk@31
   130
            putString(email.subject, toLabel: cell.subjectLabel)
dirk@31
   131
            putString(nil, toLabel: cell.summaryLabel)
dirk@32
   132
dirk@119
   133
            if let originationDate = email.originationDate {
dirk@32
   134
                let formatter = NSDateFormatter.init()
dirk@32
   135
                formatter.dateStyle = .ShortStyle
dirk@32
   136
                formatter.timeStyle = .ShortStyle
dirk@119
   137
                putString(formatter.stringFromDate(originationDate), toLabel: cell.dateLabel)
dirk@32
   138
            } else {
dirk@32
   139
                putString(nil, toLabel: cell.dateLabel)
dirk@32
   140
            }
dirk@31
   141
        }
dirk@30
   142
    }
dirk@30
   143
dirk@30
   144
}
dirk@30
   145
dirk@31
   146
extension EmailListViewController: NSFetchedResultsControllerDelegate {
dirk@31
   147
    func controllerWillChangeContent(controller: NSFetchedResultsController) {
dirk@31
   148
        tableView.beginUpdates()
dirk@30
   149
    }
dirk@30
   150
dirk@31
   151
    func controller(controller: NSFetchedResultsController,
dirk@31
   152
                    didChangeSection sectionInfo: NSFetchedResultsSectionInfo,
dirk@31
   153
                                     atIndex sectionIndex: Int,
dirk@31
   154
                                             forChangeType type: NSFetchedResultsChangeType) {
dirk@31
   155
        switch (type) {
dirk@31
   156
        case .Insert:
dirk@31
   157
            tableView.insertSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   158
                                     withRowAnimation: .Fade)
dirk@31
   159
        case .Delete:
dirk@31
   160
            tableView.deleteSections(NSIndexSet.init(index: sectionIndex),
dirk@31
   161
                                     withRowAnimation: .Fade)
dirk@31
   162
        default:
dirk@31
   163
            Log.info(comp, "unhandled changeSectionType: \(type)")
dirk@31
   164
        }
dirk@30
   165
    }
dirk@30
   166
dirk@31
   167
    func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject,
dirk@31
   168
                    atIndexPath indexPath: NSIndexPath?,
dirk@31
   169
                                forChangeType type: NSFetchedResultsChangeType,
dirk@31
   170
                                              newIndexPath: NSIndexPath?) {
dirk@40
   171
        switch type {
dirk@40
   172
        case .Insert:
dirk@40
   173
            tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   174
        case .Delete:
dirk@40
   175
            tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   176
        case .Update:
dirk@40
   177
            if let cell = tableView.cellForRowAtIndexPath(indexPath!) {
dirk@40
   178
                self.configureCell(cell as! EmailListViewCell, indexPath: indexPath!)
dirk@40
   179
            } else {
dirk@40
   180
                Log.warn(comp, "Could not find cell for changed indexPath: \(indexPath!)")
dirk@31
   181
            }
dirk@40
   182
        case .Move:
dirk@40
   183
            if newIndexPath != indexPath {
dirk@40
   184
                tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
dirk@40
   185
                tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
dirk@40
   186
            }
dirk@31
   187
        }
dirk@31
   188
    }
dirk@31
   189
dirk@31
   190
    func controllerDidChangeContent(controller: NSFetchedResultsController) {
dirk@31
   191
        tableView.endUpdates()
dirk@31
   192
    }
dirk@30
   193
}