//
//  CreateAccount2.swift
//  Mindtap_Official
//
//  Created by Lunar on 5/26/21.
//

import UIKit
import Firebase
import FirebaseAuth
import FirebaseFirestore



class CreateAccount2: UIViewController {
    @IBOutlet weak var emailEntry: UITextField!
    @IBOutlet weak var testPasswordEntry: UITextField!
    @IBOutlet weak var reTestPasswordEntry: UITextField!
    
    @IBOutlet weak var insuffInfo: UILabel!
    

    var finalFirstName = ""
    var finalLastName = ""
    var finalPhoneNumber = ""
    var finalDOB = ""



    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print(finalFirstName, finalLastName, finalPhoneNumber, finalDOB)
        
        

        // Do any additional setup after loading the view.
    }
    

    
    func validateFields() -> String? {
        
        // Check that all fields are filled in
        if emailEntry.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            testPasswordEntry.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
            reTestPasswordEntry.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
            
            return "Please fill in all fields"
            
            
        }
        
        // Check if the password is secure
        let cleanedPassword = testPasswordEntry.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        
        if Utilities.isPasswordValid(cleanedPassword) == false {
            // Password isn't secure enough
            return "Password must be 8 characters long and a special character"
            
        }
        
        return nil
    }
        
        
    
    


    @IBAction func SignUp(_ sender: UIButton) {
        
        let firstName = finalFirstName
        let lastName = finalLastName
        let phoneNumber = finalPhoneNumber
        let DOB = finalDOB
        let testPassword = testPasswordEntry.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let reTestPassword = reTestPasswordEntry.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        let error = validateFields()
        let email = emailEntry.text!.trimmingCharacters(in: .whitespacesAndNewlines)
        
        if error != nil{
            showError(error!)
            
        } else{
        
        
            if testPassword != reTestPassword{
                self.insuffInfo.text = "Paswords dont match"
                

        }
            else {

            let password = testPassword
            
            print(email, "\n", password)
          
             
    
        
            Auth.auth().createUser(withEmail: email, password: password) {( result, err) in
                //check for error
                if err != nil {
                //there was an error creating the user
                self.insuffInfo.text = "Email already exists"
                print("Error creating user info")
            }
        else {
                
                //grab user information and store in firestore
                let db = Firestore.firestore()
                
                db.collection("users").addDocument(data: [
                                                    "DOB": DOB, "firestname": firstName, "lastname": lastName, "phone": phoneNumber])
                self.transitionToHome()
            }
        
        

        
        //transition to the home screen if everything is good.
                
        
                }
            
        }
        }
    

    }


    func transitionToHome() {
        let homeViewController =
            storyboard?.instantiateViewController(identifier:
            Constants.Storyboard.homeViewController) as?
            MainMenu
        
        view.window?.rootViewController = homeViewController
        view.window?.makeKeyAndVisible()
        
        
    }
        func showError(_ message:String) {
        
        insuffInfo.text = message
        insuffInfo.alpha = 1
    }
    


}
