· 6 years ago · Feb 05, 2020, 09:40 AM
1//
2// CFLTWDocumentCell.swift
3// CapitalFirstSales
4//
5// Created by techjini on 04/07/18.
6// Copyright © 2018 Techjini Solutions. All rights reserved.
7//
8
9import UIKit
10import MobileCoreServices
11
12class CFLTWButtonCollectionViewCell: UICollectionViewCell, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
13 @IBOutlet weak var addFileButton: UIButton!
14 @IBOutlet weak var imageView: UIImageView!
15
16 var isCroppable = true
17 var delegate: CFLTWDocumentCell?
18 var documentType: CFLUploadDocumentType! = nil
19 var galleryUpload = false
20 var documentName: String?
21 var businessUnit: CFLBusinessUnit?
22 var bussinessUnitCD: [CFLBusinessUnit] = [CFLBusinessUnit.urban(.cd)]
23
24
25
26 override func awakeFromNib() {
27 super.awakeFromNib()
28 let appDelegate = UIApplication.shared.delegate as? AppDelegate
29 if let bu = CFLBusinessUnit(rawValue: appDelegate?.docUploadBU ?? "") {
30 businessUnit = bu
31 }
32 self.setUpUI()
33 }
34
35 func setUpUI() {
36 addFileButton.clipsToBounds = true
37 addFileButton.layer.cornerRadius = 5.0
38 addFileButton.layer.borderWidth = 1.0
39 addFileButton.layer.borderColor = #colorLiteral(red: 0.8901960784, green: 0.937254902, blue: 0.9647058824, alpha: 1).cgColor
40
41 if documentType == .both && galleryUpload == true {
42 imageView.image = UIImage.init(named: "add")
43 }
44 else {
45 imageView.image = UIImage.init(named: "Camera")
46 }
47 }
48
49 @IBAction func addDocument(_ sender: Any) {
50
51
52 if galleryUpload == true {
53 print("Gallery upload")
54 }
55 // For TW and UC logins, while uploading the customer photo allow only camera upload, restrict gallery and document uploads
56// if businessUnit = AppDelegate.user.businessUnit, [.TW,CFLBusinessUnit.urban(.uc)].contains(CFLBusinessUnit), documen
57 if documentType == .both && galleryUpload == true {
58 showActionSheet()
59 return
60 }
61
62 let cameraViewController = CFLCameraModule.init(self,
63 isGreyscaled: false,
64 isCroppable: self.isCroppable,
65 analyticsPrefix: "")
66 UIApplication.topViewController()?.present(cameraViewController, animated: true)
67 }
68}
69
70extension CFLTWButtonCollectionViewCell : CFLMediaCaptureDelegate {
71 func userDidCapture(_ image: UIImage) {
72 let imageAfterCompression = image.wxCompress()
73
74 userSelectedImage(image: imageAfterCompression)
75 }
76
77 func userSelectedImage(image: UIImage) {
78 let index = (delegate?.documentDataSource.startIndex) ?? 0
79 let document = delegate?.addDocument?(index, image,(Data(), filePassword: nil, orginalName: nil))
80
81 delegate?.documentDataSource.insert(document!, at: index)
82
83 delegate?.documentDataSource[index].image = image
84 delegate?.collectionView.reloadData()
85 }
86}
87
88// Document Selection Support
89extension CFLTWButtonCollectionViewCell {
90
91 func showActionSheet() {
92 let alert = UIAlertController(title: "Select One", message: nil, preferredStyle: .actionSheet)
93
94 alert.addAction(UIAlertAction(title: "Document Upload", style: .default, handler: { (action) in
95 self.chooseDocument()
96 }))
97
98 alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action) in
99
100 let cameraViewController = CFLCameraModule.init(self,
101 isGreyscaled: false,
102 isCroppable: self.isCroppable,
103 analyticsPrefix: "")
104 UIApplication.topViewController()?.present(cameraViewController, animated: true)
105
106
107 }))
108 //For CD Gallery upload is disabled and only camera and pdf upload is enabled. Changes are for documentName = "Application Form"
109 if let bu = businessUnit {
110 let isbussinessUnitCD = bussinessUnitCD.contains(bu)
111 if isbussinessUnitCD, documentName == "Application Form" {
112 //Do not add Gallery option for CD of document name "Application Form"
113 } else {
114 alert.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (action) in
115
116 if UIImagePickerController.isSourceTypeAvailable(.photoLibrary){
117
118 let imag = UIImagePickerController()
119 imag.delegate = self
120 imag.sourceType = .photoLibrary;
121 //imag.mediaTypes = [kUTTypeImage];
122 imag.allowsEditing = false
123 UIApplication.topViewController()?.present(imag, animated: true, completion: nil)
124 }
125
126 }))
127 }
128 }
129
130 alert.addAction(UIAlertAction(title: "Cancel", style: UIAlertAction.Style.cancel, handler: nil))
131
132 UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
133
134 }
135
136 func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
137 let image = info[.originalImage] as! UIImage
138 userSelectedImage(image: image)
139 UIApplication.topViewController()?.dismiss(animated: true, completion: nil)
140 }
141
142}
143
144// Document Selection Support
145extension CFLTWButtonCollectionViewCell: UIDocumentMenuDelegate,UIDocumentPickerDelegate {
146 func chooseDocument() {
147 let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
148 importMenu.delegate = self
149 importMenu.modalPresentationStyle = .formSheet
150 importMenu.addOption(withTitle: "Select Document", image: nil, order: .first, handler: { print("New Doc Requested") })
151
152 UIApplication.topViewController()?.present(importMenu, animated: true, completion: nil)
153 }
154
155 public func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
156 let myURL = url as URL
157 print("import result : \(myURL)")
158
159 guard let document = CGPDFDocument(url as CFURL) else { return }
160 print("Document password ",!document.isUnlocked)
161
162 if !document.isUnlocked { // has password
163 askForPassword(url: myURL)
164 }
165 else {
166 addDocument(with: url, password: nil)
167 }
168
169 }
170
171
172 func askForPassword(url: URL) {
173 let alert = UIAlertController(title: "Enter Password",
174 message: "Your document is password protected. Please provide the same",
175 preferredStyle: .alert)
176
177 alert.addTextField { (textField) in
178 textField.placeholder = "Enter"
179 }
180
181 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
182
183 let action = UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in
184 let textField = alert!.textFields![0]
185// print("Text field: \(textField.text)")
186
187 if textField.text != nil {
188 self.addDocument(with: url, password: textField.text)
189 }
190 else {
191 self.askForPassword(url: url)
192 }
193
194 })
195
196 alert.addAction(action)
197 alert.addAction(cancelAction)
198
199 UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
200 }
201
202
203 func addDocument(with url: URL, password: String?) {
204
205 if let pdfData = try? Data(contentsOf: url) {
206 let resourceDocPath = NSHomeDirectory().appendingFormat("/Documents/yourPDF.pdf")
207 unlink(resourceDocPath)
208
209 if let _ = URL.init(string: resourceDocPath) {
210
211 // try? pdfData.write(to: localURL)
212
213 let index = (delegate?.documentDataSource.startIndex) ?? 0
214
215
216 let document = delegate?.addDocument?(index, nil, (pdfData, filePassword: password, orginalName: url.lastPathComponent))
217
218 delegate?.documentDataSource.insert(document!, at: index)
219 delegate?.documentDataSource[index].image = UIImage.init(named: "Document")
220 delegate?.collectionView.reloadData()
221
222 }
223 }
224 }
225
226
227 public func documentMenu(_ documentMenu:UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
228 documentPicker.delegate = self
229 UIApplication.topViewController()?.present(documentPicker, animated: true, completion: nil)
230 }
231
232
233 func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
234 print("view was cancelled")
235// dismiss(animated: true, completion: nil)
236 }
237}
238
239class CFLTWDocumentCell: UITableViewCell {
240
241 @IBOutlet weak var headingLabel: UILabel!
242 @IBOutlet weak var descriptionLabel: UILabel!
243 @IBOutlet weak var collectionView: UICollectionView!
244 @IBOutlet weak var centerDescriptionLabel: UILabel!
245 @IBOutlet weak var collectionViewHeightConstraint: NSLayoutConstraint!
246 @IBOutlet weak var modifyButton: UIButton!
247
248 var addDocument:((_ index: Int, _ image: UIImage? , (Data, filePassword: String?, orginalName: String?)?) -> (CFLDocument))?
249 var removeDocument:((_ index: Int) -> ())?
250 var numberOfPages: Int = 1
251 var documentDataSource : [CFLDocument] = []
252 var isCroppable = true
253 var galleryUpload = false
254 var businessUnit: CFLBusinessUnit?
255 var documentName: String?
256// var documents: [CFLDocument]!
257
258 fileprivate let documentUploadNeeded: [CFLBusinessUnit: Bool?] = [CFLBusinessUnit.urban(.pl): true,CFLBusinessUnit.urban(.uc): true,CFLBusinessUnit.urban(.tw): true]
259 fileprivate let galleryUploadOverride: [CFLBusinessUnit: Bool?] = [CFLBusinessUnit.urban(.uc): true,CFLBusinessUnit.urban(.tw): true] // Override the gallery upload value coming from api
260 fileprivate let disallowGalleryUploadInCustomerPhotoForBUs: [CFLBusinessUnit] = [ CFLBusinessUnit.urban(.uc),CFLBusinessUnit.urban(.tw)]
261 fileprivate let allowPDFandCameraUploadForApplicationForm: [CFLBusinessUnit] = [CFLBusinessUnit.urban(.cd)]
262
263 override func awakeFromNib() {
264 super.awakeFromNib()
265 self.selectionStyle = .none
266 let appDelegate = UIApplication.shared.delegate as? AppDelegate
267 if let bu = CFLBusinessUnit(rawValue: appDelegate?.docUploadBU ?? "") {
268 businessUnit = bu
269 }
270 }
271
272 override func setSelected(_ selected: Bool, animated: Bool) {
273 super.setSelected(selected, animated: animated)
274 }
275
276 func reloadCollectionView() {
277 self.documentDataSource.removeAll()
278 self.collectionView.reloadData()
279 }
280
281 func setUpLayout(with heading: String?, subHeading: String?, mandatory: Bool) {
282 self.centerDescriptionLabel.text = ""
283 var titleText = heading
284 let optionalText = "(\(String(localize: "Optional")))"
285 if !mandatory && !(titleText?.isEmpty)! {
286 titleText = titleText! + optionalText
287 let range = (titleText!).range(of: optionalText)
288 let nsRange = NSRange(range!, in: titleText!)
289 let attributedText = NSMutableAttributedString.init(string: titleText!)
290 let attributes = [
291 NSAttributedString.Key.foregroundColor.rawValue: UIColor(red:0.58, green:0.58, blue:0.6, alpha:1),
292 NSAttributedString.Key.font : UIFont.italicSystemFont(ofSize: 12)
293 ] as! [NSAttributedString.Key : Any]
294 attributedText.addAttributes(attributes, range: nsRange)
295 self.headingLabel.attributedText = attributedText
296 } else {
297 self.headingLabel.text = titleText
298 }
299 self.descriptionLabel.text = subHeading
300 if titleText!.isEmpty {
301 self.descriptionLabel.text = ""
302 self.centerDescriptionLabel.text = subHeading
303 }
304 let collectionViewHeight = (UIScreen.main.bounds.width * 120) / 375
305 var rows = 1
306 if numberOfPages != 3 {
307 rows = numberOfPages % 3 == 0 ? numberOfPages / 3 : numberOfPages / 3 + 1
308 }
309 self.collectionViewHeightConstraint.constant = collectionViewHeight * CGFloat(rows)
310 }
311}
312
313extension CFLTWDocumentCell: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
314 func numberOfSections(in collectionView: UICollectionView) -> Int {
315 return 1
316 }
317
318 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
319 return numberOfPages
320 }
321
322 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
323 let width = collectionView.frame.size.width/3
324 return CGSize(width: width, height: width)
325 }
326
327 func collectionView(_ collectionView: UICollectionView, cellForItemAt
328 indexPath: IndexPath) -> UICollectionViewCell {
329
330 if documentDataSource.count != numberOfPages && indexPath.item == 0 {
331 let cell = collectionView.dequeueReusableCell(
332 withReuseIdentifier: "CFLTWButtonCollectionViewCell",
333 for: indexPath) as! CFLTWButtonCollectionViewCell
334 cell.isCroppable = self.isCroppable
335 cell.delegate = self
336 cell.documentName = self.documentName
337
338 let appDelegate = UIApplication.shared.delegate as? AppDelegate
339
340 cell.galleryUpload = galleryUpload
341 // Overriding the gallery upload key in case of UC and TW businessunits
342 if let bu = businessUnit, let gallUpload = galleryUploadOverride[bu], gallUpload == true {
343 cell.galleryUpload = true
344 }
345 // For UC and TW, for Customer Photo Upload the gallery upload should be hidden
346 if let bu = businessUnit, documentName == "CKYC Photograph" {
347 let isDissallowGalleryUploadForCustomerPhoto = disallowGalleryUploadInCustomerPhotoForBUs.contains(bu)
348 if isDissallowGalleryUploadForCustomerPhoto {
349 cell.galleryUpload = false
350 }
351 }
352
353 if let bu = businessUnit, documentName == "Application Form" {
354 let isallowPDFandCameraUploadForApplicationForm = allowPDFandCameraUploadForApplicationForm.contains(bu)
355 if isallowPDFandCameraUploadForApplicationForm {
356 cell.galleryUpload = true
357 cell.documentType = .both
358 }
359 }
360
361 if let bu = businessUnit, let value = documentUploadNeeded[bu], value == true {
362
363 cell.documentType = .both
364 cell.setUpUI()
365 }
366 cell.setUpUI()
367 return cell
368 } else {
369 let currentDocumentCell = collectionView.dequeueReusableCell(
370 withReuseIdentifier: "CFLTWFormCollectionViewCell",
371 for: indexPath) as! CFLTWFormCollectionViewCell
372 currentDocumentCell.documentImageContainer.layoutIfNeeded()
373 currentDocumentCell.delegate = self
374 let _ = currentDocumentCell.documentImageContainer.layer.sublayers?.filter({ (layer) -> Bool in
375 if layer is CAShapeLayer{
376 layer.removeFromSuperlayer()
377 }
378 return false
379 })
380 var index = documentDataSource.count == numberOfPages ? IndexPath(item: indexPath.item, section: indexPath.section) : IndexPath(item: indexPath.item - 1, section: indexPath.section)
381
382 if index.item < documentDataSource.count {
383 currentDocumentCell.documentImageView.image = documentDataSource[index.item].image
384 currentDocumentCell.currentDoc = documentDataSource[index.item]
385 currentDocumentCell.currentIndex = indexPath
386 currentDocumentCell.deleteDocumentImageView.isHidden = false
387 } else {
388 currentDocumentCell.deleteDocumentImageView.isHidden = true
389 currentDocumentCell.setUpLayout()
390 currentDocumentCell.currentDoc = nil
391 currentDocumentCell.documentImageView.image = UIImage()
392 }
393 currentDocumentCell.documentImageContainer.clipsToBounds = true
394 // currentDocumentCell.documentNameLabel.isHidden = true
395 currentDocumentCell.layoutIfNeeded()
396
397 currentDocumentCell.changelayoutAccordingDocument()
398 return currentDocumentCell
399 }
400 }
401}
402
403extension CFLTWDocumentCell : CFLTWFormCollectionViewCellDelegate {
404 func didDelete(document doc: CFLDocument, atIndex index: IndexPath) {
405 let indexPath = documentDataSource.count == numberOfPages ? IndexPath(item: index.item, section: index.section) : IndexPath(item: index.item - 1, section: index.section)
406 documentDataSource.remove(at: indexPath.row)
407 collectionView.reloadData()
408 self.removeDocument?(indexPath.row)
409 }
410}