//
//  LoginViewController.swift
//  BTap
//
//  Created by Chris Ki on 3/7/15.
//  Copyright (c) 2015 Jennifer Wang. All rights reserved.
//

import UIKit

import Foundation

class LoginViewController: UIViewController {

    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    
    override func viewDidLoad() {
        super.viewDidLoad()

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

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func displayMyAlertMessage(userMessage:String) {
        
        var myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
        
        // ok button
        let okAction = UIAlertAction(title:"Ok", style: UIAlertActionStyle.Default, handler:nil);
        
        myAlert.addAction(okAction);
        
        self.presentViewController(myAlert, animated:true, completion:nil);
    }

    
    
    @IBAction func loginButtonTapped(sender: AnyObject) {
        
        let userEmail = userEmailTextField.text;
        let userPassword = userPasswordTextField.text;
        
        //if (userPassword.isEmpty || userPassword.isEmpty) { return; }
        
        // *IMPORTANT: these are required for checking if username and password are correct compared to locally stored data
        //let userEmailStored = NSUserDefaults.standardUserDefaults().stringForKey("userEmail");
        //let userPasswordStored = NSUserDefaults.standardUserDefaults().stringForKey("userPassword");
        
        if (userEmail.isEmpty || userPassword.isEmpty) {
            displayMyAlertMessage("All fields are required!");
            return;
        }
        
        // Checks against the user's stored user Defaults information?
        //if ((userEmailStored != userEmail) && (userPasswordStored != userPassword)) {
        //    displayMyAlertMessage("Either username or password do not match!");
        //    return;
        //}
        
        //send user data to server side
        let myUrl = NSURL(string: "http://cgi.soic.indiana.edu/~team3/userLogin.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
        
        let postString = "email=\(userEmail)&password=\(userPassword)";

        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
        
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            
            if error != nil {
                println("error=\(error)")
                return
            }
            
            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
            
            
            if let parseJSON = json {
                var resultValue:String = parseJSON["status"] as String!;
                println("result: \(resultValue)")
                
                if(resultValue=="Success")
                {
                    // Login is Successful
                    NSOperationQueue.mainQueue().addOperationWithBlock {
                    
                    // Sets user defaults
                    NSUserDefaults.standardUserDefaults().setBool(true,forKey:"isUserLoggedIn");
                    NSUserDefaults.standardUserDefaults().synchronize();
                    
                    // Moves to HomePage
                    self.performSegueWithIdentifier("loginToHome", sender: self);
                    }
                    
                    
                }else {
                    
                    // Login was not successful
                    NSOperationQueue.mainQueue().addOperationWithBlock {
                    self.displayMyAlertMessage("Email or password does not match. Please try again.");
                    return;
                    }
                }
            
            
            }
            
        
        }
            
        task.resume()
        
    }
   
    
}
