Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 17 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
//
2
//  CommentAndRatingView.swift
3
//  twogetskills
4
//
5
//  Created by Efrain Yanez Recanatini on 7/28/22.
6
//
7
 
8
import SwiftUI
9
import AudioToolbox
10
import Network
11
import Alamofire
12
import SwiftyJSON
13
import TTGSnackbar
14
 
15
 
16
struct CommentAndRatingView: View {
17
    @EnvironmentObject private var networkMonitor : NetworkMonitor
18
    @EnvironmentObject private var appNavigation : AppNavigation
19
 
20
    @State private var capsuleTitle : String = ""
21
 
22
 
23
    @ObservedObject var commentsViewModel  : CommentAndRatingCommentsViewModel = CommentAndRatingCommentsViewModel()
24
 
25
    @ObservedObject var  capsuleViewModel : CommentAndRatingCapsuleViewModel = CommentAndRatingCapsuleViewModel()
26
 
27
    @State var refreshListComment : Bool = true
28
 
29
 
30
    @State var rating : Double = 5.0
31
    @State var comment : String = "" {
32
        didSet {
33
            if comment.count > 128 {
34
                comment =  String(comment.prefix(128))
35
                AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { return }
36
            }
37
        }
38
    }
39
 
40
    @State private var selectedType: CommentAndRatingPickerType = .introduction
41
 
42
    @State private var presentAlert : Bool = false
43
    @State private var titleAlert : String = ""
44
    @State private var messageAlert : String = ""
45
 
46
    @State private var showProgressView : Bool = false
47
 
48
    private var appData = AppData.sharedInstance
49
 
50
    var body: some View {
51
 
52
 
53
 
54
        VStack(spacing: 0)
55
        {
56
            HStack {
57
                Button(action: {
58
                    withAnimation {
59
                        appNavigation.subpageActive = .mycapsules
60
                    }
61
                }, label: {
62
 
63
 
64
                    Image(systemName: "chevron.backward")
65
                    .frame(width: 32, height: 32, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
66
                    .aspectRatio(contentMode: .fit)
67
                    .foregroundColor(networkMonitor.status == .disconnected ? Color("color_network_disconnected_foreground") : Color("color_app_bar_foreground"))
68
                })
69
                .padding(.leading, 16)
70
 
71
                Text(networkMonitor.status == .disconnected ? Config.LANG_ERROR_NETWORK_MESSAGE_SHORT :  capsuleTitle)
72
                .font(Font.custom(Config.FONT_NAME_REGULAR, size: Config.FONT_SIZE_APP_BAR_HEAD1 ))
73
                    .foregroundColor(networkMonitor.status == .disconnected ? Color("color_network_disconnected_foreground") : Color("color_app_bar_foreground"))
74
                    .padding(.leading, 4)
75
 
76
                Spacer()
77
            }
78
            .edgesIgnoringSafeArea(.top)
79
            .frame(height: 50)
80
            .background(networkMonitor.status == .disconnected ? Color("color_network_disconnected_background") : Color("color_app_bar_background"))
81
 
82
 
83
            Divider().background(networkMonitor.status == .disconnected ? Color("color_network_disconnected_background") : Color("color_app_bar_background"))
84
 
85
 
86
 
87
            CommentAndRatingImageView(capsuleModel: self.capsuleViewModel.capsule)
88
 
89
            CommentAndRatingPickerView(capsuleModel: self.capsuleViewModel.capsule, selectedType: self.$selectedType).frame(height: 48)
90
 
91
             switch self.selectedType
92
             {
93
                case .introduction :
94
                    CommentAndRatingIntroductionView(capsuleModel:  self.capsuleViewModel.capsule).padding(5)
95
 
96
                case .comments :
97
                    if self.commentsViewModel.comments.count == 0 {
98
                        CommentAndRatingCommentListEmptyView()
99
                    } else {
100
 
101
                        ScrollView {
102
                            LazyVStack  {
103
                                //ForEach(0..<self.comments.count) { index in
104
 
105
                                ForEach(self.commentsViewModel.comments) { commentItem in
106
                                    CommentAndRatingCommentListItemView(comment: commentItem) {
107
                                        deleteComment(id: commentItem.id, linkDelete: commentItem.link_delete  )
108
 
109
                                    }
110
                                }
111
 
112
                            }
113
                        }
114
                    }
115
 
116
 
117
                   // CommentAndRatingCommentListView(comments: self.commentsViewModel.comments, showProgressView: self.$showProgressView).border(Color.blue, width: 1)
118
 
119
                default :
120
                    CommentAndRatingPostCommentView(
121
                        capsuleModel: self.capsuleViewModel.capsule, comment: self.$comment, rating: self.$rating) {
122
                        sendPostComment()
123
                    }
124
 
125
            }
126
 
127
            Spacer()
128
        }
129
        .background(Color("color_picker_background"))
130
        .onAppear {
131
 
132
            self.capsuleViewModel.fetch(capsuleUuid: appData.capsuleUuidActive, userUuid: appData.userUuid)
133
 
134
            if self.capsuleViewModel.capsule.name.count > Constants.APP_BAR_TITLE_MAX_LENGTH {
135
                self.capsuleTitle = String(Array(self.capsuleViewModel.capsule.name)[0...Constants.APP_BAR_TITLE_MAX_LENGTH]) + "..."
136
            } else {
137
                self.capsuleTitle = self.capsuleViewModel.capsule.name
138
            }
139
 
140
            self.reloadComments()
141
 
142
 
143
        } .alert(isPresented: $presentAlert) {
144
            Alert(
145
                title: Text(self.titleAlert),
146
                message: Text(self.messageAlert),
147
                dismissButton: .default(Text(Config.LANG_COMMON_OK))
148
            )
149
        }
150
    }
151
 
152
    func reloadComments()
153
    {
154
        self.commentsViewModel.comments.removeAll()
155
 
156
        if !self.capsuleViewModel.capsule.linkComments.isEmpty && networkMonitor.status == .connected {
157
 
158
            let headerSecurity : HeaderSecurity = HeaderSecurity()
159
 
160
            let headers: HTTPHeaders = [
161
                .init(name: Constants.HTTP_HEADER_SECURITY_TOKEN, value: appData.deviceUuid),
162
                .init(name: Constants.HTTP_HEADER_SECURITY_SECRET, value: headerSecurity.secret),
163
                .init(name: Constants.HTTP_HEADER_SECURITY_CREATED, value: String(headerSecurity.created)),
164
                .init(name: Constants.HTTP_HEADER_SECURITY_RAND, value: String(headerSecurity.rand)),
165
                .accept(Constants.HTTP_HEADER_ACCEPT)
166
            ]
167
 
168
            //print("URL Comments: \(self.capsuleViewModel.capsule.linkComments)")
169
 
170
            commentsViewModel.comments.removeAll()
171
 
172
            AF.request(self.capsuleViewModel.capsule.linkComments, method: .get, headers: headers).responseJSON{(response) in
173
                    self.showProgressView = false
174
                    switch response.result {
175
                        case .success:
176
                            let json = try? JSON(data: response.data!)
177
 
178
                           // print("json : \(json)")
179
 
180
                            if json?["success"] ?? "" != false {
181
 
182
                                if json?["data"]["capsule"] != nil  {
183
                                    let sTotalComments = json?["data"]["capsule"]["total_comments"].string ?? ""
184
 
185
                                    let sTotalRating = json?["data"]["capsule"]["total_rating"].string ?? ""
186
 
187
                                    capsuleViewModel.capsule.totalComments = Int(sTotalComments) ?? 0
188
                                    capsuleViewModel.capsule.totalRating = Decimal(Double(sTotalRating) ?? 0)
189
 
190
                                    let capsuleDao = CapsuleDao.sharedInstance
191
                                    capsuleDao.update(capsule: capsuleViewModel.capsule)
192
                                }
193
 
194
                                if json?["data"]["comments"] != nil  {
195
                                    var newComment : CommentAndRatingComment
196
                                    for jcomment in json!["data"]["comments"]
197
                                    {
198
                                        newComment = CommentAndRatingComment()
199
                                        newComment.date = jcomment.1["date"].string ?? ""
200
                                        newComment.rating = Decimal(Double(jcomment.1["rating"].string ??  "") ?? 0)
201
                                        newComment.fullname = jcomment.1["fullname"].string ?? ""
202
                                        newComment.comment = jcomment.1["comment"].string ?? ""
203
                                        newComment.image = jcomment.1["image"].string ?? ""
204
                                        newComment.link_delete = jcomment.1["link_delete"].string ?? ""
205
                                        let sDate = jcomment.1["date"].string ?? ""
206
 
207
                                        let formatterService = DateFormatter()
208
                                        formatterService.dateFormat = Constants.FORMAT_DATETIME_SERVICE
209
                                        if let date = formatterService.date(from: sDate) {
210
 
211
                                            let dateFormatterUser = DateFormatter()
212
                                            dateFormatterUser.dateFormat = Constants.FORMAT_DATE_TIME_24
213
                                            newComment.date =  dateFormatterUser.string(from: date)
214
 
215
 
216
                                        }
217
 
218
 
219
 
220
 
221
                                        commentsViewModel.comments.append(newComment)
222
                                    }
223
                                }
224
 
225
 
226
 
227
                            } else {
228
                                let message = json?["data"].string ?? ""
229
                                if !message.isEmpty {
230
                                    self.titleAlert = Config.LANG_ERROR_GENERIC_TITLE
231
                                    self.messageAlert = message
232
                                    self.presentAlert = true
233
                                }
234
                            }
235
 
236
                           return
237
 
238
                        case .failure :
239
                            self.titleAlert = Config.LANG_ERROR_COMMUNICATION_TITLE
240
                            self.messageAlert = Config.LANG_ERROR_COMMUNICATION_MESSAGE
241
                            self.presentAlert = true
242
 
243
                            return
244
                    }
245
                }
246
 
247
        }
248
 
249
 
250
    }
251
 
252
    func sendPostComment() {
253
 
254
        let now = Date()
255
        let dateFormatter = DateFormatter()
256
        dateFormatter.dateFormat = Constants.FORMAT_DATETIME_SERVICE
257
        let dateOn = dateFormatter.string(from: now)
258
 
259
        showProgressView = true
260
        let parameters = [
261
            Constants.POST_COMMENT_FIELD_COMMENT: comment,
262
            Constants.POST_COMMENT_FIELD_RATING: "\(Int(rating))",
263
            Constants.POST_COMMENT_FIELD_ADDED_ON: dateOn
264
        ]
265
 
266
        let headerSecurity : HeaderSecurity = HeaderSecurity()
267
 
268
        let headers: HTTPHeaders = [
269
            .init(name: Constants.HTTP_HEADER_SECURITY_TOKEN, value: appData.deviceUuid),
270
            .init(name: Constants.HTTP_HEADER_SECURITY_SECRET, value: headerSecurity.secret),
271
            .init(name: Constants.HTTP_HEADER_SECURITY_CREATED, value: String(headerSecurity.created)),
272
            .init(name: Constants.HTTP_HEADER_SECURITY_RAND, value: String(headerSecurity.rand)),
273
            .accept(Constants.HTTP_HEADER_ACCEPT)
274
        ]
275
 
276
       // print("URL POST COMMENT : \(capsuleViewModel.capsule.linkComments)")
277
 
278
        self.showProgressView = true
279
        AF.request(capsuleViewModel.capsule.linkCommentAdd, method: .post, parameters: parameters, encoding: URLEncoding.default, headers: headers).responseJSON{(response) in
280
            self.showProgressView = false
281
 
282
            switch response.result {
283
                case .success:
284
 
285
                    let json = try? JSON(data: response.data!)
286
 
287
                    print("json : \(json)")
288
 
289
                    if json?["success"] ?? "" != false {
290
 
291
 
292
                        if json?["data"]["comment"] != nil  {
293
 
294
                            let now = Date()
295
                            let dateFormatter = DateFormatter()
296
                            dateFormatter.dateFormat = Constants.FORMAT_DATETIME_SERVICE
297
                            let dateOn = dateFormatter.string(from: now)
298
 
299
                            let link_delete =  json?["data"]["comment"]["link_delete"].string ?? ""
300
 
301
 
302
                            var newComment = CommentAndRatingComment()
303
                            newComment.date = dateOn
304
                            newComment.image = appData.userImage
305
                            newComment.fullname = "\(appData.userFirstname) \(appData.userLastname)"
306
                            newComment.rating = Decimal(rating)
307
                            newComment.comment = comment
308
                            newComment.link_delete = link_delete
309
 
310
                            commentsViewModel.prepend(newComment: newComment)
311
 
312
                            self.comment = ""
313
                            self.rating = 5
314
                            self.selectedType = .comments
315
                         }
316
 
317
 
318
                        if json?["data"]["capsule"] != nil  {
319
                            let sTotalComments = json?["data"]["capsule"]["total_comments"].string ?? ""
320
 
321
                            let sTotalRating = json?["data"]["capsule"]["total_rating"].string ?? ""
322
 
323
                            capsuleViewModel.capsule.totalComments = Int(sTotalComments) ?? 0
324
                            capsuleViewModel.capsule.totalRating = Decimal(Double(sTotalRating) ?? 0)
325
 
326
                            let capsuleDao = CapsuleDao.sharedInstance
327
                            capsuleDao.update(capsule: capsuleViewModel.capsule)
328
                        }
329
 
330
 
331
 
332
                        if json?["data"]["message"] != nil  {
333
                            let snackbar = TTGSnackbar(message: json?["data"]["message"].string ?? "", duration: .long)
334
                            snackbar.show()
335
 
336
                        }
337
 
338
 
339
 
340
                    } else {
341
                        let message = json?["data"].string ?? ""
342
                        if !message.isEmpty {
343
                            self.titleAlert = Config.LANG_ERROR_GENERIC_TITLE
344
                            self.messageAlert = message
345
                            self.presentAlert = true
346
                        }
347
                    }
348
 
349
                   return
350
 
351
                case .failure :
352
                    self.titleAlert = Config.LANG_ERROR_COMMUNICATION_TITLE
353
                    self.messageAlert = Config.LANG_ERROR_COMMUNICATION_MESSAGE
354
                    self.presentAlert = true
355
 
356
                    return
357
            }
358
        }
359
 
360
 
361
    }
362
 
363
    func deleteComment(id : String, linkDelete : String) {
364
 
365
        showProgressView = true
366
 
367
        let headerSecurity : HeaderSecurity = HeaderSecurity()
368
 
369
        let headers: HTTPHeaders = [
370
            .init(name: Constants.HTTP_HEADER_SECURITY_TOKEN, value: appData.deviceUuid),
371
            .init(name: Constants.HTTP_HEADER_SECURITY_SECRET, value: headerSecurity.secret),
372
            .init(name: Constants.HTTP_HEADER_SECURITY_CREATED, value: String(headerSecurity.created)),
373
            .init(name: Constants.HTTP_HEADER_SECURITY_RAND, value: String(headerSecurity.rand)),
374
            .accept(Constants.HTTP_HEADER_ACCEPT)
375
        ]
376
 
377
        self.showProgressView = true
378
        AF.request(linkDelete, method: .post, encoding: URLEncoding.default, headers: headers).responseJSON{(response) in
379
            self.showProgressView = false
380
 
381
            switch response.result {
382
                case .success:
383
 
384
                    let json = try? JSON(data: response.data!)
385
 
386
                   // print("json : \(json)")
387
 
388
                    if json?["success"] ?? "" != false {
389
 
390
 
391
 
392
 
393
 
394
                        if json?["data"]["capsule"] != nil  {
395
                            let sTotalComments = json?["data"]["capsule"]["total_comments"].string ?? ""
396
 
397
                            let sTotalRating = json?["data"]["capsule"]["total_rating"].string ?? ""
398
 
399
                            capsuleViewModel.capsule.totalComments = Int(sTotalComments) ?? 0
400
                            capsuleViewModel.capsule.totalRating = Decimal(Double(sTotalRating) ?? 0)
401
 
402
                            let capsuleDao = CapsuleDao.sharedInstance
403
                            capsuleDao.update(capsule: capsuleViewModel.capsule)
404
                        }
405
 
406
 
407
 
408
                        if json?["data"]["message"] != nil  {
409
                            let snackbar = TTGSnackbar(message: json?["data"]["message"].string ?? "", duration: .long)
410
                            snackbar.show()
411
 
412
                        }
413
 
414
                        self.commentsViewModel.removeItem(id: id)
415
 
416
 
417
 
418
                    } else {
419
                        let message = json?["data"].string ?? ""
420
                        if !message.isEmpty {
421
                            self.titleAlert = Config.LANG_ERROR_GENERIC_TITLE
422
                            self.messageAlert = message
423
                            self.presentAlert = true
424
                        }
425
                    }
426
 
427
                   return
428
 
429
                case .failure :
430
                    self.titleAlert = Config.LANG_ERROR_COMMUNICATION_TITLE
431
                    self.messageAlert = Config.LANG_ERROR_COMMUNICATION_MESSAGE
432
                    self.presentAlert = true
433
 
434
                    return
435
            }
436
        }
437
 
438
 
439
    }
440
}
441
 
442
struct CommentAndRatingView_Previews: PreviewProvider {
443
    static var previews: some View {
444
        CommentAndRatingView()
445
    }
446
}
447
 
448