From 6f19beac9147159f3d9f2d249b01e06b84bd336b Mon Sep 17 00:00:00 2001
From: jakob <jakob.bode@fu-berlin.de>
Date: Thu, 10 Jan 2019 13:35:46 +0100
Subject: [PATCH] handle contacts in table view and show detail for doubletap

---
 enzevalos_iphone/Intro.storyboard             | 42 ++++++++-
 enzevalos_iphone/IntroContactCell.swift       |  4 +-
 .../IntroContactTableViewController.swift     | 86 +++++++++++++------
 enzevalos_iphone/IntroTableView.swift         |  9 +-
 enzevalos_iphone/TravelIntroCoordinator.swift | 53 ++++++++++--
 5 files changed, 155 insertions(+), 39 deletions(-)

diff --git a/enzevalos_iphone/Intro.storyboard b/enzevalos_iphone/Intro.storyboard
index ba5cc332..cc8e8320 100644
--- a/enzevalos_iphone/Intro.storyboard
+++ b/enzevalos_iphone/Intro.storyboard
@@ -30,7 +30,7 @@
                             <textView clipsSubviews="YES" multipleTouchEnabled="YES" contentMode="center" bounces="NO" scrollEnabled="NO" showsHorizontalScrollIndicator="NO" showsVerticalScrollIndicator="NO" bouncesZoom="NO" editable="NO" textAlignment="center" selectable="NO" translatesAutoresizingMaskIntoConstraints="NO" id="Lr2-gv-nYg">
                                 <rect key="frame" x="18.5" y="75.5" width="337.5" height="467"/>
                                 <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
-                                <mutableString key="text">Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.</mutableString>
+                                <string key="text">Lorem ipsum dolor sit er elit lamet, consectetaur cillium adipisicing pecu, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Nam liber te conscient to factor tum poen legum odioque civiuda.</string>
                                 <fontDescription key="fontDescription" type="system" pointSize="22"/>
                                 <textInputTraits key="textInputTraits" autocapitalizationType="sentences"/>
                             </textView>
@@ -158,10 +158,15 @@
                     <simulatedNavigationBarMetrics key="simulatedTopBarMetrics"/>
                     <connections>
                         <outlet property="doubleTapRecognizer" destination="EJr-Kc-9MN" id="51d-fg-3bM"/>
+                        <outlet property="singleTapRecognizer" destination="2yG-Ee-Lqr" id="bGl-0F-tXD"/>
                     </connections>
                 </tableViewController>
                 <placeholder placeholderIdentifier="IBFirstResponder" id="8GW-9X-WHB" userLabel="First Responder" sceneMemberID="firstResponder"/>
-                <tapGestureRecognizer id="2yG-Ee-Lqr"/>
+                <tapGestureRecognizer id="2yG-Ee-Lqr">
+                    <connections>
+                        <action selector="singleTap:" destination="QVX-gn-Y6B" id="Tbt-fA-hi1"/>
+                    </connections>
+                </tapGestureRecognizer>
                 <tapGestureRecognizer numberOfTapsRequired="2" id="EJr-Kc-9MN">
                     <connections>
                         <action selector="doubleTap:" destination="QVX-gn-Y6B" id="asu-ot-QnX"/>
@@ -170,5 +175,38 @@
             </objects>
             <point key="canvasLocation" x="2111" y="-224"/>
         </scene>
+        <!--View Controller-->
+        <scene sceneID="20K-0C-K8D">
+            <objects>
+                <viewController id="5rU-Nz-nnq" sceneMemberID="viewController">
+                    <view key="view" contentMode="scaleToFill" id="dI1-xe-ou2">
+                        <rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
+                        <autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
+                        <subviews>
+                            <imageView userInteractionEnabled="NO" contentMode="scaleToFill" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" translatesAutoresizingMaskIntoConstraints="NO" id="N2Y-wr-yZt">
+                                <rect key="frame" x="67" y="42" width="240" height="128"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
+                            </imageView>
+                            <label opaque="NO" userInteractionEnabled="NO" contentMode="left" horizontalHuggingPriority="251" verticalHuggingPriority="251" fixedFrame="YES" text="Label" textAlignment="natural" lineBreakMode="tailTruncation" baselineAdjustment="alignBaselines" adjustsFontSizeToFit="NO" translatesAutoresizingMaskIntoConstraints="NO" id="aVy-vp-ZXu">
+                                <rect key="frame" x="166" y="191" width="42" height="21"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
+                                <fontDescription key="fontDescription" type="system" pointSize="17"/>
+                                <nil key="textColor"/>
+                                <nil key="highlightedColor"/>
+                            </label>
+                            <button opaque="NO" contentMode="scaleToFill" fixedFrame="YES" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="aME-hX-KrC">
+                                <rect key="frame" x="313" y="20" width="46" height="30"/>
+                                <autoresizingMask key="autoresizingMask" flexibleMaxX="YES" flexibleMaxY="YES"/>
+                                <state key="normal" title="Button"/>
+                            </button>
+                        </subviews>
+                        <color key="backgroundColor" white="1" alpha="1" colorSpace="custom" customColorSpace="genericGamma22GrayColorSpace"/>
+                        <viewLayoutGuide key="safeArea" id="kqf-A3-Awr"/>
+                    </view>
+                </viewController>
+                <placeholder placeholderIdentifier="IBFirstResponder" id="EVl-zp-ySA" userLabel="First Responder" sceneMemberID="firstResponder"/>
+            </objects>
+            <point key="canvasLocation" x="2841" y="-224"/>
+        </scene>
     </scenes>
 </document>
diff --git a/enzevalos_iphone/IntroContactCell.swift b/enzevalos_iphone/IntroContactCell.swift
index 670aecd3..331a16f2 100644
--- a/enzevalos_iphone/IntroContactCell.swift
+++ b/enzevalos_iphone/IntroContactCell.swift
@@ -13,14 +13,14 @@ class IntroContactCell: UITableViewCell {
     @IBOutlet weak var nameLabel: UILabel!
     @IBOutlet weak var planeImage: UIImageView!
     
-    var enzContact: KeyRecord? {
+    var enzContact: EnzevalosContact? {
         didSet {
             if let con = enzContact {
                 var cont: Contact
                 if let contact = con.cnContact {
                     cont = contact
                 } else {
-                    cont = con.ezContact
+                    cont = con
                 }
                 nameLabel.text = cont.name
                 contactImage.image = cont.getImageOrDefault()
diff --git a/enzevalos_iphone/IntroContactTableViewController.swift b/enzevalos_iphone/IntroContactTableViewController.swift
index d3e6dcc0..95f8748a 100644
--- a/enzevalos_iphone/IntroContactTableViewController.swift
+++ b/enzevalos_iphone/IntroContactTableViewController.swift
@@ -10,12 +10,14 @@ import Foundation
 
 class IntroContactTableViewController: UITableViewController {
     //var contacts: [String: [EnzevalosContact]] = [:]
-    var contacts: [String: [String]] = [:]
+    var contacts: [String: [(EnzevalosContact, PersistentKey, [Mail_Address])]] = [:]
+    var selected: Set<IndexPath> = Set<IndexPath>.init()
     
+    @IBOutlet var singleTapRecognizer: UITapGestureRecognizer!
     @IBOutlet var doubleTapRecognizer: UITapGestureRecognizer!
     static let storyboardID = "contactTableViewController"
     
-    static func storyboardInstance(contacts: [String: [String]]) -> IntroContactTableViewController? {
+    static func storyboardInstance(contacts: [String: [(EnzevalosContact, PersistentKey, [Mail_Address])]]) -> IntroContactTableViewController? {
         let storyboard = UIStoryboard(name:
             "Intro", bundle: nil)
         if let controller = storyboard.instantiateViewController(withIdentifier: storyboardID) as? IntroContactTableViewController {
@@ -26,11 +28,17 @@ class IntroContactTableViewController: UITableViewController {
     }
     
     override func viewDidLoad() {
+        tableView.addGestureRecognizer(singleTapRecognizer)
         tableView.addGestureRecognizer(doubleTapRecognizer)
+        singleTapRecognizer.require(toFail: doubleTapRecognizer)
     }
     
     override func viewDidAppear(_ animated: Bool) {
         super.viewDidAppear(animated)
+        for index in selected {
+            tableView.selectRow(at: index, animated: false, scrollPosition: .none)
+            tableView.delegate?.tableView!(tableView, didSelectRowAt: index)
+        }
         tableView.reloadData()
     }
     
@@ -60,7 +68,8 @@ class IntroContactTableViewController: UITableViewController {
         }
         
         if let rows = contacts[intToAlphabet(value: indexPath.section)] {
-            cell.nameLabel.text = rows[indexPath.row]
+            //cell.nameLabel.text = rows[indexPath.row]
+            cell.enzContact = rows[indexPath.row].0
         }
         return cell
     }
@@ -104,13 +113,38 @@ class IntroContactTableViewController: UITableViewController {
         return titles
     }
     
+    @IBAction func singleTap(_ sender: Any) {
+        print("single")
+        if let sender = sender as? UITapGestureRecognizer {
+            let point = sender.location(in: tableView)
+            if let index = tableView.indexPathForRow(at: point) {
+                print(index.section, " ", index.row)
+                tableView(tableView, didDeselectRowAt: index)
+                if let selected = tableView.indexPathsForSelectedRows, selected.contains(index) {
+                    tableView.deselectRow(at: index, animated: false)
+                    tableView.delegate?.tableView!(tableView, didDeselectRowAt: index)
+                    _ = self.selected.remove(index)
+                } else {
+                    tableView.selectRow(at: index, animated: false, scrollPosition: .none)
+                    tableView.delegate?.tableView!(tableView, didSelectRowAt: index)
+                    selected.insert(index)
+                }
+            }
+        }
+    }
+    
     @IBAction func doubleTap(_ sender: Any) {
-//        if let sender = sender as? UITapGestureRecognizer {
-//            sender.location(in: <#T##UIView?#>)
-//        }
-//        if let cell = UIScreen.main.focusedView as? IntroContactCell {
-//            print(cell.nameLabel.text)
-//        }
+        print("double")
+        if let sender = sender as? UITapGestureRecognizer {
+            let point = sender.location(in: tableView)
+            if let index = tableView.indexPathForRow(at: point), let cell = tableView.cellForRow(at: index) as? IntroContactCell {
+                print(index.section, " ", index.row)
+                //tableView(tableView, didDeselectRowAt: index)
+                
+                self.present(IntroDescriptionViewController.storyboardInstance(description: cell.nameLabel.text!)!, animated: true, completion: nil)
+                //show(IntroDescriptionViewController.storyboardInstance(description: cell.nameLabel.text!)!, sender: nil)
+            }
+        }
     }
     
     func intToAlphabet(value: Int) -> String {
@@ -126,21 +160,19 @@ class IntroContactTableViewController: UITableViewController {
 //
 //}
 
-//extension IntroContactTableViewController: UIViewControllerPreviewingDelegate {
-//    
-//    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
-//        guard let indexPath = tableView.indexPathForRow(at: location) else {
-//            return nil
-//        }
-//        
-//        let detailViewController = createDetailViewControllerIndexPath(indexPath: indexPath)
-//        
-//        return detailViewController
-//    }
-//    
-//    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
-//        
-//    }
-//    
-//    
-//}
+extension IntroContactTableViewController: UIViewControllerPreviewingDelegate {
+    
+    func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
+        guard let indexPath = tableView.indexPathForRow(at: location) else {
+            return nil
+        }
+        
+        return IntroDescriptionViewController.storyboardInstance(description: "test")
+    }
+    
+    func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
+        
+    }
+    
+    
+}
diff --git a/enzevalos_iphone/IntroTableView.swift b/enzevalos_iphone/IntroTableView.swift
index 349e70c6..5b28eeea 100644
--- a/enzevalos_iphone/IntroTableView.swift
+++ b/enzevalos_iphone/IntroTableView.swift
@@ -9,9 +9,14 @@
 import Foundation
 
 class IntroTableView: UITableView {
+    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
+        
+    }
+    
     override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
         for touch in touches {
-            if touch.tapCount == 2 {
+            print(touch.force)
+            if touch.tapCount == 2 || touch.force > 1.0 {
                 let point = touch.location(in: self)
                 let index = indexPathForRow(at: point)
                 if let index = index {
@@ -19,6 +24,6 @@ class IntroTableView: UITableView {
                 }
             }
         }
-        super.touchesEnded(touches, with: event)
+        //super.touchesEnded(touches, with: event)
     }
 }
diff --git a/enzevalos_iphone/TravelIntroCoordinator.swift b/enzevalos_iphone/TravelIntroCoordinator.swift
index c9288e8e..556e0cd1 100644
--- a/enzevalos_iphone/TravelIntroCoordinator.swift
+++ b/enzevalos_iphone/TravelIntroCoordinator.swift
@@ -19,13 +19,9 @@ class TravelIntroCoordinator {
         controllers.append(backupController)
         let describeContactsController = IntroButtonViewController.storyboardInstance(description: "W", buttonText: "Kontakte auswählen")!
         controllers.append(describeContactsController)
-        var contacts: [String: [String]] = [:]
-        contacts["A"] = ["Adam", "Alfred", "Anna"]
-        contacts["B"] = ["Bob"]
-        contacts["D"] = []
-        contacts["X"] = ["Xenia", "X"]
+        var contacts = getSecureContacts()
         let contactViewController = IntroContactTableViewController.storyboardInstance(contacts: contacts)!
-        controllers.append(contactViewController)
+        //controllers.append(contactViewController)
         let pageViewController = IntroPageViewController.storyboardInstance(orderedViewControllers: controllers)
         pageViewController?.title = "Erklärung"
         
@@ -36,4 +32,49 @@ class TravelIntroCoordinator {
         
         return pageViewController!
     }
+    
+    static func getSecureContacts() -> [String: [(EnzevalosContact, PersistentKey, [Mail_Address])]] {
+        let dataHandler = DataHandler.handler
+        var contacts = dataHandler.getContacts()
+        contacts = contacts.filter({c in return c.hasKey})
+        var result: [String: [(EnzevalosContact, PersistentKey, [Mail_Address])]] = [:]
+        for c in contacts {
+            var keys:[PersistentKey] = []
+            var addrsPerKey: [PersistentKey: [Mail_Address]] = [:]
+            for adr in c.addresses {
+                if let adr = adr as? Mail_Address, adr.hasKey, let key = adr.primaryKey, adr.address != UserManager.loadUserValue(.userAddr) as? String ?? "" {
+                    if !keys.contains(key) {
+                        keys.append(key)
+                        addrsPerKey[key] = [adr]
+                    } else {
+                        addrsPerKey[key]?.append(adr)
+                    }
+                }
+            }
+            if keys.count > 0 {
+                for key in keys {
+                    var tuple = (c, key, addrsPerKey[key]!)
+                    if let entry = result[getFirstChar(from: c)] {
+                        result[getFirstChar(from: c)]!.append(tuple)
+                    } else {
+                        result[getFirstChar(from: c)] = [tuple]
+                    }
+                }
+            }
+        }
+        return result
+    }
+    
+    static func getFirstChar(from contact: EnzevalosContact) -> String {
+        if let char = contact.name.first, let unicode = char.unicodeScalars.first {
+            let diffUpper = abs(Int(unicode.value) - Int(UnicodeScalar("A").value))
+            let diffLower = abs(Int(unicode.value) - Int(UnicodeScalar("a").value))
+            if diffUpper >= 0 && diffUpper < 26 {
+                return String(unicode)
+            } else if diffLower >= 0 && diffLower < 26, let upperUnicode = UnicodeScalar(Int(UnicodeScalar("A").value)+diffLower) {
+                return String(upperUnicode)
+            }
+        }
+        return "#"
+    }
 }
-- 
GitLab