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

import UIKit

class ModifyingProfileViewController: UIViewController {

    @IBOutlet weak var userNameTextField: UITextField!
    @IBOutlet weak var userFirstnameTextField: UITextField!
    @IBOutlet weak var userLastnameTextField: UITextField!
    @IBOutlet weak var userEmailTextField: UITextField!
    @IBOutlet weak var userPasswordTextField: UITextField!
    @IBOutlet weak var repeatPasswordTextField: 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 saveChangeButtonTapped(sender: AnyObject) {
        
        let userName = userNameTextField.text;
        let userFirstname = userFirstnameTextField.text;
        let userLastname = userLastnameTextField.text;
        let userEmail = userEmailTextField.text;
        let userPassword = userPasswordTextField.text;
        let userRepeatPassword = repeatPasswordTextField.text;
        
        // Check for empty fields
        if (userName.isEmpty || userFirstname.isEmpty || userLastname.isEmpty || userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty) {
            
            // Display alert message
            
            displayMyAlertMessage("All fields are required!");
            
            return;
        }
        
        // check if username length is more than 20
        if (countElements(userName) > 20) {
            
            // Display alert message
            displayMyAlertMessage("Username length should not be longer than 20 characters!");
            return;
        }
        
        // Check if passwords match
        if (userPassword != userRepeatPassword) {
            
            // Display and alert message, and return to not let the user continue
            
            displayMyAlertMessage("Passwords do not match!");
            
            return;
        }
        
        // check if password length is more than 20
        if (countElements(userPassword) > 20) {
            
            // Display alert message
            displayMyAlertMessage("Password length should not be longer than 15 characters!");
            return;
        }
        
        // if there's no "@" or "." typed in email textfield, display error message
        if (!contains(userEmail, "@") || !contains(userEmail, ".")) {
            displayMyAlertMessage("Please type an email!");
            return;
        }
        
        // lines for local data save for profile use
        // for username display on profile page
        NSUserDefaults.standardUserDefaults().setObject(userName, forKey:"userName");
        
        NSUserDefaults.standardUserDefaults().synchronize();
        // **
        
        
        //Send data to server side
        let myUrl = NSURL(string: "http://cgi.soic.indiana.edu/~team3/userModify.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
        
        let postString = "username=\(userName)&fname=\(userFirstname)&lname=\(userLastname)&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 = parseJSON["status"] as? String
                println("result: \(resultValue)")
                
                
                var isUserRegistered:Bool = false;
                if(resultValue=="Success") { isUserRegistered = true; }
                
                var messageToDisplay:String = parseJSON["message"] as String!;
                if(!isUserRegistered)
                {
                    messageToDisplay = parseJSON["message"] as String!;
                }
                
                
                dispatch_async(dispatch_get_main_queue(), {
                    
                    // Display alert message with confirmation
                    var myAlert = UIAlertController(title:"Alert", message:messageToDisplay, preferredStyle: UIAlertControllerStyle.Alert);
                    
                    let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.Default){ action in
                        self.dismissViewControllerAnimated(true, completion: nil);
                    }
                    
                    myAlert.addAction(okAction);
                    self.presentViewController(myAlert, animated: true, completion: nil)
                    
                }); // end of dispatch_async()
            } // end of if
            
        } // end of let task
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
        task.resume()
        
        // send back to login view
        var loginViewController: LoginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("LoginViewController") as LoginViewController
        
        
        
    }
    

    @IBAction func cancelButtonTapped(sender: AnyObject) {
        self.dismissViewControllerAnimated(true, completion:nil);
    }


}
