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

import UIKit

class ProfileViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
    
    @IBOutlet weak var profileTableView: UITableView!
    
    @IBOutlet weak var myImageView: UIImageView!
    
    
    @IBOutlet weak var usernameLabel: UILabel!
    
    var arrayOfProfileUsers: [ProfileUser] = [ProfileUser]()

    override func viewDidLoad() {
        super.viewDidLoad()
        
        myImageView.image = UIImage(named: "profilePic.png")

        self.setUpProfileUsers()
        // need to change these lines to php
        // these are for loading up locally saved username data and display it as a label on the view
        let usernameStored = NSUserDefaults.standardUserDefaults().stringForKey("userName");
        
        // this changes label's text with username that's locally saved in the server
        usernameLabel.text = usernameStored
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    
    // load the different users to the array of User
    func setUpProfileUsers() {
        
        var writeReviewStored = NSUserDefaults.standardUserDefaults().stringForKey("writeReview2")
        var userNameStored = NSUserDefaults.standardUserDefaults().stringForKey("userName")
        var ratingNumStored = NSUserDefaults.standardUserDefaults().integerForKey("ratingNum2")
        
        var review1 = ProfileUser(barbeer: "bar: bbq restaurant", review: "pretty meh", rating: 2)
        var review2 = ProfileUser(barbeer: "beer: ice mint", review: "pretty good", rating: 4)
        var review3 = ProfileUser(barbeer: "beer: orange fanta", review: "I can make it better", rating: 1)
        //
        var review4 = ProfileUser(barbeer: userNameStored!, review: writeReviewStored!, rating: ratingNumStored)
        
        arrayOfProfileUsers.append(review1)
        arrayOfProfileUsers.append(review2)
        arrayOfProfileUsers.append(review3)
        arrayOfProfileUsers.append(review4)
    }
    
    // number of cells
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arrayOfProfileUsers.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: ProfileCell = tableView.dequeueReusableCellWithIdentifier("ProfileCell") as ProfileCell
        
        
        let reviewB = arrayOfProfileUsers[indexPath.row]
        // check out ProfileUser.swift and ProfileCell.swift for correct variable names
        cell.setCell(reviewB.barbeer, reviewLabelText: reviewB.review, ratingLabelInt: reviewB.rating)
        
        
        return cell
    }
    
    /*
    @IBAction func uploadButtonTapped(sender: AnyObject) {
        
        myImageUploadRequest() // calling function
    }
    
    @IBAction func selectPhotoButtonTapped(sender: AnyObject) {
        
        var myPickerController = UIImagePickerController()
        myPickerController.delegate = self; // set delegate to self
        myPickerController.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
        // select and present myPickerController to the user
        self.presentViewController(myPickerController, animated: true, completion: nil)
    }
    */
    
    
    @IBAction func FavButtonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("profileToFav", sender: self);
    }
    
    @IBAction func NearbyButtonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("profileToNearby", sender: self);
    }
    
    @IBAction func HomeButtonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("profileToHome", sender: self);
    }
    
    @IBAction func SearchButtonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("profileToSearch", sender: self);
    }
    
    @IBAction func ProfileButtonTapped(sender: AnyObject) {
        self.performSegueWithIdentifier("profileToProfile", sender: self);
    }
    
    
    @IBAction func modifyButtonTapped(sender: AnyObject) {
        
        var modifyingProfileViewController: ModifyingProfileViewController = self.storyboard?.instantiateViewControllerWithIdentifier("ModifyingProfileViewController") as ModifyingProfileViewController
        
        self.presentViewController(modifyingProfileViewController, animated: true, completion: nil)
    }
    
    
    
    
    
    
    
    
    
    /*
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
        
    {
        myImageView.image = info[UIImagePickerControllerOriginalImage] as? UIImage
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    // this function is triggered when user taps on the "upload image" button
    func myImageUploadRequest()
    {
        // URL should be pointing to our serverside script
        // "http://www.swiftdeveloperblog.com/http-post-example-script/"
        let myUrl = NSURL(string: "http://cgi.soic.indiana.edu/~team3/image_upload.php");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
        
        let param = [
            "firstName" : "Chris",
            "lastName" : "Ki",
            "userId" : "1" // userId is important to indicate image's owner
        ]
        
        let boundary = generateBoundaryString()
        
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        // imiageData will be the data holder
        let imageData = UIImageJPEGRepresentation(myImageView.image, 1)
        
        if(imageData==nil) { return; }
        
        // filePathKey is needed for referring to images on the server side
        request.HTTPBody = createBodyWithParameters(param, filePathKey: "file", imageDataKey: imageData, boundary: boundary)
        
        myActivityIndicator.startAnimating();
        
        //sending and executing request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
            data, response, error in
            
            if error != nil {
                println("error=\(error)")
                return
            }
            // responses back
            // You can print out response object
            println("******* response = \(response)")
            
            // Print out reponse body
            let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("****** response data = \(responseString!)")
            
            // * maybe json part is not needed
            var err: NSError?
            var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary
            //
            
            dispatch_async(dispatch_get_main_queue(),{
                self.myActivityIndicator.stopAnimating()
                //self.myImageView.image = nil; // for removing image from the v iew once the uploading to the server is complete - just another way of confirmation
            });
            
        }
        
        task.resume()
        
    }
    
    
    func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
        
        var body = NSMutableData();
        
        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("–\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }
        
        let filename = "user-profile.jpg" // filename will be this when the image is uploaded to the server
        
        let mimetype = "image/jpg" // image type will be jpg
        
        body.appendString("–\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")
        body.appendData(imageDataKey)
        body.appendString("\r\n")
        
        body.appendString("–\(boundary)–\r\n")
        
        return body
    }
    
    func generateBoundaryString() -> String {
        return "Boundary-\(NSUUID().UUIDString)"
    }
    */
    
} // class ends

/*
extension NSMutableData {
    
    // makes data to be appended as NSUTF8StringEncoding
    func appendString(string: String) {
        let data = string.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
        appendData(data!)
    }
}
*/
