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

import UIKit
import Accounts
import Social

class ViewController: UIViewController {
    @IBOutlet weak var txtPost: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func postMessage(sender: AnyObject) {
        let accountStore: ACAccountStore = ACAccountStore()
        let accountType: ACAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
        
        accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: {(granted, error) -> Void in
            if (granted)
            {
                let arrayOfAccounts: NSArray = accountStore.accountsWithAccountType(accountType)
                
                if (arrayOfAccounts.count > 0)
                {
                    let twitterAccount: ACAccount = arrayOfAccounts.lastObject as! ACAccount
                    
                    var message = Dictionary<String, AnyObject>()
                    message["status"] = self.txtPost.text
                    
                    let requestURL: NSURL = NSURL(string: "https://api.twitter.com/1.1/statuses/update.json")!
                    
                    let postRequest: SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.POST, URL: requestURL, parameters: message)
                    
                    postRequest.account = twitterAccount
                    
                    postRequest.performRequestWithHandler({(responseData, urlResponse, error) ->
                        Void in
                    })
                }
            } else {
                // Handle failure to get account access
            }
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


}

