//
//  LoginVC.swift
//  OrderPicky
//
//  Created by Vijith on 03/02/22.
//

import UIKit
import Foundation

class LoginVC: UIViewController,UITextFieldDelegate {

    let valid = validation()
    
   // var modelClass : MobRegClass!
    
   
    
    @IBOutlet weak var mobNo: UITextField!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!
  
   
    @IBOutlet weak var mobTFView: UIView!
    @IBOutlet weak var enterBtn: UIButton!
    
    
    
    override func viewDidLoad() {
       
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        mobNo.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        
        
        self.setui()
        self.addKeyboardObserver()
        initializeHideKeyboard()
        
        
    }
    override func viewWillDisappear(_ animated: Bool) {
        self.removeKeyboardObserver()
    }
    
   
    func setui(){
        self.mobNo.setLeftPaddingPoints(10)
        self.mobTFView.layer.cornerRadius = 8.0
        self.enterBtn.layer.cornerRadius = 8.0
        
    }
   
   
    
    func initializeHideKeyboard(){
        //Declare a Tap Gesture Recognizer which will trigger our dismissMyKeyboard() function
        let tap: UITapGestureRecognizer = UITapGestureRecognizer(
            target: self,
            action: #selector(dismissMyKeyboard))
        //Add this tap gesture recognizer to the parent view
        view.addGestureRecognizer(tap)
    }
    @objc func dismissMyKeyboard(){
        //endEditing causes the view (or one of its embedded text fields) to resign the first responder status.
        //In short- Dismiss the active keyboard.
        view.endEditing(true)
    }
    // to limit text count
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        let maxLength :Int = 10
        let currentString: NSString = (textField.text ?? "") as NSString
        let newString: NSString =
            currentString.replacingCharacters(in: range, with: string) as NSString
        return newString.length <= maxLength
    }
    
    func showActivity()
    {
        DispatchQueue.main.async {
            self.view.isUserInteractionEnabled = false
            self.activityIndicator.startAnimating()
        }
    }
    func hideActivity()
    {
        DispatchQueue.main.async {
            self.view.isUserInteractionEnabled = true
            self.activityIndicator.stopAnimating()
        }
    }
    /*
    func postData(mobNo : String)
    {
        if Reachability.isConnectedToNetwork() == false
        {
            let destViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "noconnectID") as! NoConnectionVC
            self.navigationController?.pushViewController(destViewController, animated: true)
        }
        self.showActivity()
        let url =  RestApiManager.sharedInstance.baseURL + "model3/mobile/verify"
       // let parameter:[String:String] = ["mobile" : mobNo]
        let obj = URL(string: url)
        // let finalbody = try!  JSONSerialization.data(withJSONObject: parameter, options: [])
        
 // This is the common way to pass parameters as formdata. Here only one parameter ie mobile: <number> { you can use code from line no: 46 to 82 as common with values changed as per the requirments }
        
        let parameters = [
          [
            "key": "mobile",
            "value": mobNo,
            "type": "text"
          ]] as [[String : Any]]

        let boundary = "Boundary-\(UUID().uuidString)"
        var body = ""
        var error: Error? = nil
        for param in parameters {
          if param["disabled"] == nil {
            let paramName = param["key"]!
            body += "--\(boundary)\r\n"
            body += "Content-Disposition:form-data; name=\"\(paramName)\""
            let paramType = param["type"] as! String
            if paramType == "text" {
              let paramValue = param["value"] as! String
              body += "\r\n\r\n\(paramValue)\r\n"
            } else {
              let paramSrc = param["src"] as! String
                do{
              let fileData = try NSData(contentsOfFile:paramSrc, options:[]) as Data
              let fileContent = String(data: fileData, encoding: .utf8)!
              body += "; filename=\"\(paramSrc)\"\r\n"
                + "Content-Type: \"content-type header\"\r\n\r\n\(fileContent)\r\n"
            }
                catch
                {
                    print(error)
                }
          }
        }
        }
        body += "--\(boundary)--\r\n";
        let postData = body.data(using: .utf8)
        
        var request = URLRequest(url: obj!)
        request.httpMethod = "POST"
        request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        request.httpBody = postData
       // request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        
        URLSession.shared.dataTask(with: request ) { (data , response , error) in
            
            self.hideActivity()
            
            guard let data = data,error == nil else{
                DispatchQueue.main.async {
                    self.showSnackBar(Message: error?.localizedDescription ?? "Something Wrong", duration: .middle)
                }
                
               //print("something wrong")
                return
            }
            
            print(data)
            if let response = response as? HTTPURLResponse {
                print("Response HTTP Status code: \(response.statusCode)")
                print(response)
            
                if response.statusCode != 200
                {
                    DispatchQueue.main.async {
                        self.showSnackBar(Message:  response.description ?? "Something Went Wrong", duration: .middle)
                    }
                   
                    return
                }
            }
            
            
            let finaldata = try! JSONDecoder().decode(MobRegClass.self, from: data)
            print(finaldata)
            let msg = finaldata.message
            DispatchQueue.main.async {
            if(finaldata.status == 1)
            {
                self.modelClass = finaldata
                DispatchQueue.main.async {
               //     self.showSnackBar(Message: msg ?? "Success", duration: .middle)
                }
                
                //UserDefaults.standard.set(true, forKey: "isLoggedIn")
             
                let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OtpVC") as! OtpVC
                vc.mobPass = self.mobNo.text!
                vc.modelClass = self.modelClass
                self.navigationController?.pushViewController(vc, animated: true)
            }
            if(finaldata.status == 0){
               // self.performSegue(withIdentifier: "ToReg", sender: self)
                
                let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUpVC") as! SignUpVC
                vc.mob = self.mobNo.text!
                self.navigationController?.pushViewController(vc, animated: true)
            }
                else
            {
                DispatchQueue.main.async {
                self.showSnackBar(Message: msg ?? "Something wrong", duration: .middle)
                }
                return
            }
                
              
                
            }
        }.resume()
    
    }
  */
    
    @IBAction func OnTapEnter(_ sender: Any)
    {
        
        
//        let mob : String = (self.mobNo.text?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))!
//        let validMobile = self.valid.validaPhoneNumber(phoneNumber: mob)
//        if (validMobile == false)
//        {
//           // displayAlert(message: "Invalid mobile number")
//            DispatchQueue.main.async
//            {
//           // self.showSnackBar(Message:"Invalid mobile number" ,duration: .middle)
//            }
//
//            return
//        }
      //  postData(mobNo: self.mobNo.text!)
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "OtpVC") as! OtpVC
        
        self.navigationController?.pushViewController(vc, animated: true)
}
    @IBAction func OnTapSignUp(_ sender: Any) {
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SignUpVC") as! SignUpVC
        
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
