//
//  ViewController.swift
//  CoreDataDemo
//
//  Created by MAC on 18/02/21.
//  Copyright © 2021 Angelzz. All rights reserved.
//

import UIKit
import CoreData

class ViewController: UIViewController {

    @IBOutlet weak var nameText: UITextField!
    
    @IBOutlet weak var ageText: UITextField!
    
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

    
    override func viewDidLoad() {
        super.viewDidLoad()
//        self.fetchCorrData()
    }

    @IBAction func loginClicked(_ sender: UIButton) {
        let context = appDelegate.persistentContainer.viewContext
        let entity = NSEntityDescription.entity(forEntityName: "Student", in: context)
        let newUser = NSManagedObject(entity: entity!, insertInto: context)
        
        newUser.setValue(self.nameText.text, forKey: "age")
        newUser.setValue(self.ageText.text, forKey: "name")
        
        do {
           try context.save()
          } catch {
           print("Failed saving")
        }
        self.fetchCorrData()
    }
    
    func fetchCorrData()
    {
        let context = appDelegate.persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
        //request.predicate = NSPredicate(format: "age = %@", "12")
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            for data in result as! [NSManagedObject] {
                print("age--->",data.value(forKey: "age") as! String)
                print("name--->",data.value(forKey: "name") as! String)
                
            }
            
        } catch {
            
            print("Failed")
        }
        self.removeData()
    }
    
    func removeData()
    {
        let context = appDelegate.persistentContainer.viewContext
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Student")
        //request.predicate = NSPredicate(format: "age = %@", "12")
        request.returnsObjectsAsFaults = false
        do {
            let result = try context.fetch(request)
            context.delete(result[1] as! NSManagedObject)
            print(result[1])
            for data in result as! [NSManagedObject] {
                print("age--->",data.value(forKey: "age") as! String)
                print("name--->",data.value(forKey: "name") as! String)

            }
            
        } catch {
            
            print("Failed")
        }
    }
}

