Proyectos de Subversion Iphone Microlearning - Inconcert

Rev

Rev 19 | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

//
//  ProfileView.swift
//  twogetskills
//
//  Created by Efrain Yanez Recanatini on 5/4/22.
//

import Foundation
import SwiftUI
import Alamofire
import TTGSnackbar

struct ProfileView: View {
    @EnvironmentObject private var appNavigation : AppNavigation
    @EnvironmentObject private var networkMonitor : NetworkMonitor
    
    @State private var showGlobalAlert : Bool = false
    @State private var titleGlobalAlert : String = ""
    @State private var messageGlobalAlert : String = ""
    
    
    private var userExtendedPointViewModel : UserExtendedPointViewModel = UserExtendedPointViewModel()

    private var appData = Environment(\.appData).wrappedValue
    
    
    var body: some View {
        GeometryReader { geometry in
            VStack(spacing: 0) {
                HStack {
                    Image("logo")
                    .resizable()
                    .frame(width: 32, height: 32, alignment: .center)
                    .aspectRatio(contentMode: .fit)
                        .foregroundColor(networkMonitor.status == .disconnected ? Color("color_network_disconnected_foreground") : Color("color_app_bar_foreground"))
                    .padding(.leading, 16)
                 
                    
                    Text(networkMonitor.status == .disconnected ? Config.LANG_ERROR_NETWORK_MESSAGE_SHORT :   Config.LANG_TAB_BAR_BUTTON_PROFILE)
                    .font(Font.custom(Config.FONT_NAME_REGULAR, size: Config.FONT_SIZE_APP_BAR_HEAD1 ))
                        .foregroundColor(networkMonitor.status == .disconnected ? Color("color_network_disconnected_foreground") : Color("color_app_bar_foreground"))
                    .padding(.leading, 4)
                    
                    Spacer()
  
                    /*
                    Button(action: {
                        DispatchQueue.main.async() {
                            appNavigation.subpageActive = AppMainSubPage.deletaccount
                        }
                       
                    }, label: {
                        Image(uiImage: UIImage(named: "ui_delete") ?? UIImage())
                        .resizable()
                        .frame(width: 24, height: 24, alignment: .center)
                        .aspectRatio(contentMode: .fit)
                        .foregroundColor(Color("color_network_disconnected_foreground"))
                        .padding(.trailing, 16)
                    })*/
                    
                    
                    Button(action: {
                        let snackbar = TTGSnackbar(message: Config.LANG_SIGNOUT_MESSAGE, duration: .long)

                        // Action 1
                        snackbar.actionText = Config.LANG_COMMON_YES
                        snackbar.actionTextColor = UIColor( Color("color_snackbar_button_yes"))
                        snackbar.actionBlock = { (snackbar) in signout() }

               
                        snackbar.secondActionText = Config.LANG_COMMON_NO
                        snackbar.secondActionTextColor = UIColor(Color("color_snackbar_button_no"))
                        snackbar.secondActionBlock = { (snackbar) in }
                           
                        snackbar.show()
                       
                    }, label: {
                        Image(uiImage: UIImage(named: "ui_exit_app") ?? UIImage())
                        .resizable()
                        .frame(width: 24, height: 24, alignment: .center)
                        .aspectRatio(contentMode: .fit)
                        .foregroundColor(Color("color_network_disconnected_foreground"))
                        .padding(.trailing, 16)
                    })
                }
                .edgesIgnoringSafeArea(.top)
                .frame(height: 50)
                .background(networkMonitor.status == .disconnected ? Color("color_network_disconnected_background") : Color("color_app_bar_background"))
                
        
                Divider().background(networkMonitor.status == .disconnected ? Color("color_network_disconnected_background") : Color("color_app_bar_background"))
                
            ZStack(alignment: .top) {
                
                
                Rectangle()
                    .foregroundColor(Color("color_app_bar_background"))
                    .edgesIgnoringSafeArea(.top)
                    .frame(height: 70)
                
                
                HStack {
                    
                    if appData.userImage.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {
                         Image("logo")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(height: Config.PROFILE_IMAGE_SIZE)
                            .clipShape(Circle())
                            .overlay(Circle().stroke(Color.white, lineWidth: 4))
                            .shadow(radius: 10)
                           
                           
                        
                    } else {
                        CustomAsyncImageProfile(
                            url: URL(string: appData.userImage.trimmingCharacters(in: .whitespacesAndNewlines))!,
                            placeholder: { Text(Config.LANG_COMMON_LOADING).font(.footnote).foregroundColor(.black)},
                            image: {
                                Image(uiImage: $0)
                                    .resizable()
                                    
                            }
                        )
                    }
                }.padding(10)
            }
            VStack(spacing: 5) {
                VStack(spacing: 5) {
                    Text("\(appData.userFirstname) \(appData.userLastname)" )
                        .bold()
                        .font(.title)
                        .foregroundColor(Color("color_textview_foreground"))
                    
                    Text("\(appData.userEmail)")
                        .font(.body)
                        .foregroundColor(Color("color_textview_foreground"))
                }.padding()

 
            }.background(Color("color_card_view_background"))
            
            ScrollView {
                ForEach(0..<self.userExtendedPointViewModel.points.count) { i in
                    UserExtendedPointView(userExtendedPoint: self.userExtendedPointViewModel.points[i])
                        .listRowInsets(.init()).frame(width: geometry.size.width, height: 70, alignment: /*@START_MENU_TOKEN@*/.center/*@END_MENU_TOKEN@*/)
                }
            }
            .background(Color("color_card_view_background"))
                
            Spacer()
                
                Button(action: {
                    DispatchQueue.main.async() {
                        appNavigation.subpageActive = AppMainSubPage.deletaccount
                    }
                }, label: {
                    Text(Config.LANG_DELETE_ACCOUNT_TITLE)
                    .font(Font.custom(Config.FONT_NAME_REGULAR, size: 13))
                    .frame(width: UIScreen.main.bounds.width - 32, height: 35)
                    .foregroundColor(Color("color_button_foreground"))
                    .background(Color("color_button_background"))
                    .border(Color("color_button_border"), width: Config.BUTTON_BORDER_SIZE)
                    .cornerRadius(Config.BUTTON_BORDER_RADIUS)
                })
                .padding(.top, 16)
                .padding(.leading, 16)
                .padding(.trailing, 16)
        }.onAppear {
            userExtendedPointViewModel.loadAll()
        }.alert(isPresented: $showGlobalAlert) {
            Alert(
                title: Text(self.titleGlobalAlert),
                message: Text(self.messageGlobalAlert),
                dismissButton: .default(Text(Config.LANG_COMMON_OK))
            )
        }
        }
    }
    
    private func signout() -> Void {
        
        if networkMonitor.status == .disconnected {
        
            self.titleGlobalAlert = Config.LANG_ERROR_NETWORK_TITLE
            self.messageGlobalAlert = Config.LANG_ERROR_NETWORK_MESSAGE_LONG
            self.showGlobalAlert  = true
        } else {
            let headerSecurity = HeaderSecurity()
            let headers: HTTPHeaders = [
                .init(name: Constants.HTTP_HEADER_SECURITY_TOKEN, value: appData.deviceUuid),
                .init(name: Constants.HTTP_HEADER_SECURITY_SECRET, value: headerSecurity.secret),
                .init(name: Constants.HTTP_HEADER_SECURITY_CREATED, value: String(headerSecurity.created)),
                .init(name: Constants.HTTP_HEADER_SECURITY_RAND, value: String(headerSecurity.rand)),
                .accept(Constants.HTTP_HEADER_ACCEPT)
            ]
            
            AF.request(Config.URL_SIGNOUT, method: .post, headers: headers).responseJSON{(response) in
                switch response.result {
                    case .success:
                        let now = Date()
                        let dateFormatter = DateFormatter()
                        dateFormatter.dateFormat = Constants.FORMAT_DATETIME_SERVICE
                        let dateOn = dateFormatter.string(from: now)
                            
                            
                        var userLog = UserLogModel()
                        userLog.activity = Constants.USER_LOG_ACTIVITY_SIGNOUT
                        userLog.userUuid = appData.userUuid
                        userLog.addedOn = dateOn
                       
                        let userLogDao = UserLogDao()
                        userLogDao.insert(record: userLog)
                            
                        var json : [String: Any] = userLog.toJson()
                        json[Constants.SYNC_ADAPTER_DATA_TYPE_FIELD_NAME] = Constants.SYNC_ADAPTER_DATA_TYPE_MICROLEARNING_USER_LOG
                                    
                        var sync = SyncModel();
                        sync.type = Constants.SYNC_ADAPTER_TYPE_SYNC
                        if let theJSONData = try?  JSONSerialization.data(withJSONObject: json, options: .prettyPrinted),
                           let data = String(data: theJSONData, encoding: String.Encoding.ascii) {
                                sync.data = data
                            }
                             
                        let syncDao = SyncDao()
                        syncDao.insert(record : sync)
      
                        appData.userEmail = ""
                        appData.userFirstname = ""
                        appData.userLastname = ""
                        appData.userUuid = ""
                        appData.userImage = ""
                        appData.save()
                        
                            
                        appNavigation.pageActive = .goodbye
                        break;
                            
                    case .failure:
                        self.titleGlobalAlert = Config.LANG_ERROR_COMMUNICATION_TITLE
                        self.messageGlobalAlert = Config.LANG_ERROR_COMMUNICATION_MESSAGE
                        self.showGlobalAlert = true
                                
                        break;
                }
            }
        }
    }
}


struct ProfileView_Previews: PreviewProvider {
    static var previews: some View {
        ProfileView()
    }
}