//
//  ViewController.swift
//  FacebookSDKPost
//
//  Created by Keith Welch on 1/1/16.
//  Copyright © 2016 Keith Welch. All rights reserved.
//

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class ViewController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var txtPost: UITextView!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        if (FBSDKAccessToken.currentAccessToken() == nil)
        {
            NSLog("Not logged in...")
        }
        else
        {
            NSLog("Logged in...")
        }
        
        let loginButton = FBSDKLoginButton()
        loginButton.readPermissions = ["public_profile", "email", "user_friends"]
        loginButton.publishPermissions = ["publish_actions"]
        loginButton.center = self.view.center
        loginButton.delegate = self
        self.view.addSubview(loginButton)
    }

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
    {
        if error == nil
        {
            NSLog("Login complete.")
        }
        else
        {
            NSLog(error.localizedDescription)
        }
        
    }
    
    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
    {
        NSLog("User logged out...")
    }

    @IBAction func postMessage(sender: AnyObject) {
        if (FBSDKAccessToken.currentAccessToken().hasGranted("publish_actions")) {
            let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/feed", parameters: ["message": "hello world"], HTTPMethod: "POST")
            
            graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
                
                if ((error) != nil)
                {
                    // Process error
                    NSLog("Error: \(error)")
                }
                else
                {
                    NSLog("Success")
                }
            })
        }
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

