Sunday, 12 August 2018

//
//  ViewController.swift
//  tableCellButton
//
//

import UIKit

//:- TableViewCell
class TableViewCell: UITableViewCell {
    
    @IBOutlet weak var btLeft: UIButton!
    @IBOutlet weak var btnRight: UIButton!
    
    var follow = Bool()
    var Bl = Bool()
    var leftBtnTapped  : ((TableViewCell) -> Void)?
    var RightBtnTapped : ((TableViewCell) -> Void)?
    override func awakeFromNib() {
        super.awakeFromNib()
      
    }
    
    override func layoutSubviews() {
        
        
        
        if follow{
            btLeft.backgroundColor = UIColor.green
        }else if !follow{
            btLeft.backgroundColor = UIColor.orange
        }
        
        if Bl{
            btnRight.backgroundColor = UIColor.green
        }else if !Bl{
            btnRight.backgroundColor = UIColor.orange
        }
        
        
    }
    @IBAction func left(_ sender: UIButton) {
        self.leftBtnTapped?(self)
    }
    
    @IBAction func Right(_ sender: UIButton) {
        self.RightBtnTapped?(self)
    }
    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
    
}




//:ViewController

class ViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return leftarr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tblView.dequeueReusableCell(withIdentifier: "cell")as! TableViewCell
        cell.follow = leftarr.object(at: indexPath.row) as! Bool
        cell.Bl = rightarr.object(at: indexPath.row) as! Bool
        
        cell.leftBtnTapped = {btn in
            
            
            
            if cell.follow{
                
                self.leftarr.replaceObject(at: indexPath.row, with: false)
            }else{
                self.leftarr.replaceObject(at: indexPath.row, with: true)
            }
            
            
            print("left button\(indexPath.row)")
            self.tblView.reloadData()
        }
        
        
        cell.RightBtnTapped = {btn in
            if cell.Bl{
                self.rightarr.replaceObject(at: indexPath.row, with: false)
            }else{
                self.rightarr.replaceObject(at: indexPath.row, with: true)
            }
            self.tblView.reloadData()
            print("right button\(indexPath.row)")
        }
        
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("dsfd")
    }
    
    var leftarr = NSMutableArray()
    var rightarr = NSMutableArray()
    @IBOutlet weak var tblView: UITableView!
    override func viewDidLoad() {
        super.viewDidLoad()
        leftarr = [true,false,false,true,false]
        rightarr = [false,true,true,false,true]
        // Do any additional setup after loading the view, typically from a nib.
    }

}



//::;;;;;;;;;;;;;;;;;;;;;;;;;;

//Check Screen Size

/*let IS_IPHONE_5 = (fabs(Double(UIScreen.main.bounds.size.height) - Double(568)) < DBL_EPSILON)


#define IS_IPHONE_5_5s_5c_SE (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)568) < DBL_EPSILON)
#define IS_IPHONE_6_6s_7_8 (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)667) < DBL_EPSILON)
#define IS_IPHONE_6_6s_7_8_PLUS (fabs((double)[[UIScreen mainScreen]bounds].size.height - (double)736) < DBL_EPSILON)*/




//FOR SCREEN SHOT

/*UIGraphicsBeginImageContext(_vwTopShot.frame.size);
[_vwTopShot.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *viewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

//store all the images into array
imgArray =[[NSMutableArray alloc]init];
[imgArray addObject:viewImage];*/


// Directory SaveData or Retrieve
/*http://www.ios-developer.net/iphone-ipad-programmer/development/file-saving-and-loading/using-the-document-directory-to-store-files*/








//Utility Class


import Foundation
import UIKit



class utility : NSObject{
    
    let topController = UIApplication.topViewController()
    
    func pushViewControl(ViewControl:String){
        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: ViewControl)
        let topVC = UIApplication.topViewController()
        topVC?.navigationController?.pushViewController(controller, animated: true)
    }
    
    
    //MARK:- Display alert with completion
    
    func displayAlertWithCompletion(title:String,message:String,control:[String],completion:@escaping (String)->()){
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        for str in control{
            
            let alertAction = UIAlertAction(title: str, style: .default, handler: { (action) in
                
                completion(str)
            })
            
            alertController.addAction(alertAction)
        }
        
        
        // let topController = UIApplication.topViewController()
        topController?.present(alertController, animated: true, completion: nil)
        
    }
    
    
    //MARK:- Display alert without completion
    
    func displayAlert(title:String,message:String,control:[String]){
        
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .alert)
        
        for str in control{
            
            let alertAction = UIAlertAction(title: str, style: .default, handler: { (action) in
                
                
            })
            
            alertController.addAction(alertAction)
        }
        
        topController?.present(alertController, animated: true, completion: nil)
        
    }
    
    
    
    
    
    
    //getToken
    func getToken() -> String {
        if let token = UserDefaults.standard.value(forKey: "token")as? String{
            return token
        }
        return "dsf242gsadg25424"
    }

}

func isValidEmail(testStr:String) -> Bool {
    // print("validate calendar: \(testStr)")
    let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
    
    let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
    return emailTest.evaluate(with: testStr)
}

func isCodeValid(_ code : String) -> Bool
{
    let characterset = CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
    if code.rangeOfCharacter(from: characterset.inverted) != nil {
        print("string contains special characters")
        return false
    }
    else{
        return true
    }
}



//phone validation

func myMobileNumberValidate(_ number: String?) -> Bool {
    let numberRegEx = "[0-9]{10}"
    let numberTest = NSPredicate(format: "SELF MATCHES %@", numberRegEx)
    if numberTest.evaluate(with: number) == true {
        return true
    }
    else {
        return false
    }
}



//pincode validation

func isValidPincode(value: String) -> Bool {
    if value.characters.count == 6{
        return true
    }
    else{
        return false
    }
}

//Password Validation

func isPasswordSame(password: String , confirmPassword : String) -> Bool {
    if password == confirmPassword{
        return true
    }else{
        return false
    }
}


//Password length validation

func isPwdLenth(password: String , confirmPassword : String) -> Bool {
    if password.characters.count <= 7 && confirmPassword.characters.count <= 7{
        return true
    }else{
        return false
    }
}




extension UIApplication {
    class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
        if let navigationController = controller as? UINavigationController {
            return topViewController(controller: navigationController.visibleViewController)
        }
        if let tabController = controller as? UITabBarController {
            if let selected = tabController.selectedViewController {
                return topViewController(controller: selected)
            }
        }
        if let presented = controller?.presentedViewController {
            return topViewController(controller: presented)
        }
        return controller
    }
}

//Mp3 play
/*
https://stackoverflow.com/questions/34563329/how-to-play-mp3-audio-from-url-in-ios-swift

Control centre
https://stackoverflow.com/questions/47059049/control-audio-outside-app-in-ios*/


//PlaceHolder

@IBDesignable
class CustomTxtFld: UITextField {
}
extension UITextField{
    @IBInspectable var placeHolderColor: UIColor? {
        get {
            return self.placeHolderColor
        }
        set {
            self.attributedPlaceholder = NSAttributedString(string:self.placeholder != nil ? self.placeholder! : "", attributes:[NSAttributedStringKey.foregroundColor: newValue!])
        }
    }
}


//Image Designable

@IBDesignable
class CustomImageView: UIImageView {
    @IBInspectable var borderColor: UIColor? = UIColor.clear {
        didSet {
            layer.borderColor = self.borderColor?.cgColor
        }
    }
    
    @IBInspectable var borderWidth: CGFloat = 0 {
        didSet {
            layer.borderWidth = self.borderWidth
        }
    }
    
    @IBInspectable var cornerRadius: CGFloat = 0 {
        didSet {
            layer.cornerRadius = self.cornerRadius
            layer.masksToBounds = self.cornerRadius > 0
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    override func draw(_ rect: CGRect) {
        self.layer.cornerRadius = self.cornerRadius
        self.layer.borderWidth = self.borderWidth
        self.layer.borderColor = self.borderColor?.cgColor
    }
}


// MVVM ::


class LoginModel{
    
    var id: String?
    var phone: String?
    var email: String?
    var password: String?
    
    
    
    func loginDict(UserDetail:[String:Any]){
        
        self.id             = UserDetail["id"] as? String ?? ""
        self.phone          = UserDetail["phone"] as? String ?? ""
        self.email          = UserDetail["email"] as? String ?? ""
        self.password       = UserDetail["password"] as? String ?? ""
        
        UserDefaults.standard.set(UserDetail, forKey: "user")
        
    }
}

//viewModel
class loginViewModel{
    
    let objLoginModel = LoginModel()
    var LoginArr = [LoginModel]()
    func login(text:String,completion: @escaping (Bool,String) -> ()) {
        
        
        let param = ["email":text,
                     
                     "token":utility().getToken(),
                     ]
        
        let url = "BaseUrl" + "loginUrl"
        postDataToServer(url: url, parameters: param) { (dict) in
            print(dict)
            let msg = dict.value(forKey: "message")as! String
            let success = dict.value(forKey: "success")as! String
            if let user = dict.value(forKey: "user")as? [String : Any]{
                
                
                
                
                if success == "true"{
                    print(user)
                    self.objLoginModel.loginDict(UserDetail: user)
                    
                    
                    completion(true,msg)
                }else{
                    completion(false,msg)
                }
            }else{
                completion(false,msg)
            }
        }
        
        
    }
}


///:APi Helper
//import Alamofire

func postDataToServer (url: String, parameters: [String: Any], completion: @escaping (NSDictionary) -> ()) {
    
   /* Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in
        
        guard response.result.isSuccess else {
            print(response.result.error ?? "Some Error")
            completion([:])
            return
        }
        
        let dict : NSDictionary = response.result.value as! NSDictionary
        completion (dict)
        
    }*/
}


// View Controller
class StartScreenViewController: UIViewController{
var objStartScreenViewModel = loginViewModel()
    override func viewDidLoad() {

        objStartScreenViewModel.login(text: "tfZip.text!", completion: { (success, msg) in
        })

}
}



//:::::::::
//CReate root controller

class example{
    func check(){
    if UserDefaults.standard.bool(forKey: "alreadyLogin"){
    self.AlreadyLogin()
}
else{
    self.SlideOutMethod()
}
    }
func  AlreadyLogin()
{
  //  let tabBar: UITabBarController = self.window?.rootViewController as! UITabBarController
   // tabBar.selectedIndex = 0
}

func  SlideOutMethod()
{
    /*let story = UIStoryboard(name: "Main", bundle: nil)
    let centerViewController = story.instantiateViewController(withIdentifier: "LoginViewController") as! LoginViewController
    let centerNav = UINavigationController(rootViewController: centerViewController)
    
    centerNav.isNavigationBarHidden=true
    window?.rootViewController = centerNav
    window?.makeKeyAndVisible()*/
    
}

}