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

import UIKit
import Accounts
import Social

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet weak var tblPosts: UITableView!
    let cellID = "CellID"
    var dataSource: NSArray!

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

    @IBAction func getPosts(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
                    
                    let requestURL: NSURL = NSURL(string: "https://api.twitter.com/1.1/statuses/home_timeline.json")!
                    
                    var parameters = Dictionary<String, AnyObject>()
                    parameters["count"] = 25
                    parameters["include_entities"] = 1
                    
                    let request: SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, URL: requestURL, parameters: parameters)
                    
                    request.account = twitterAccount
                    
                    request.performRequestWithHandler({(responseData, urlResponse, error) ->
                        Void in
                        
                        do {
                            self.dataSource = try (NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers) as? NSArray)!
                            
                            if (self.dataSource.count != 0) {
                                dispatch_async(dispatch_get_main_queue()) {
                                    self.tblPosts.dataSource = self
                                    self.tblPosts.reloadData()
                                }
                            }
                        }
                        catch let error as NSError {
                            NSLog(error.description)
                        }
                    })
                }
            } else {
                // Handle failure to get account access
            }
        })
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCellWithIdentifier(cellID)
        if cell == nil {
            cell = UITableViewCell(style: .Value1, reuseIdentifier: cellID)
        }
        
        let post: NSDictionary = dataSource[indexPath.row] as! NSDictionary
        
        cell!.textLabel!.text = post["text"] as? String

        return cell!;
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

