//
//  ViewController.swift
//  UsingSLRequest
//
//  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 tblAccounts: UITableView!
    let cellID = "CellID"
    var dataSource: NSArray!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        GetAccounts()
   }
    
    func GetAccounts() {
        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)
                {
                    self.dataSource = arrayOfAccounts;
                    
                    if (self.dataSource.count != 0) {
                        dispatch_async(dispatch_get_main_queue()) {
                            self.tblAccounts.dataSource = self
                            self.tblAccounts.reloadData()
                        }
                    }
                }
            } 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 twitterAccount: ACAccount = dataSource[indexPath.row] as! ACAccount
        
        cell!.textLabel!.text = twitterAccount.username
        return cell!;
    }

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


}

