//
//  User.swift
//  TwitterClient
//
//  Created by Lilian Ngweta on 2/23/16.
//  Copyright © 2016 Lilian Ngweta. All rights reserved.
//

import UIKit

//static let userDidLogoutNotification = "UserDidLogout"
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
//let userDidLogoutNotification = "userDidLogoutNotification"

class User: NSObject {
    
    var name: String?
    var screenname:String?
    var profileImageURL: String?
    var tagline: String?
    var dictionary: NSDictionary
    var profileImageBackgroundURL: String?    
    
    var profileTweets: Int?
    var profileFollowing: Int?
    var profileFollowers: Int?
    
    
    init(dictionary: NSDictionary) {
        
        self.dictionary = dictionary
        
        name = dictionary["name"] as? String
        screenname = dictionary["screen_name"] as? String
        profileImageURL = dictionary["profile_image_url"] as? String
        tagline = dictionary["description"] as? String
        
        profileImageBackgroundURL = dictionary["profile_background_image_url"] as? String
        
        profileTweets = dictionary["statuses_count"] as? Int
        profileFollowing = dictionary["friends_count"] as? Int
        profileFollowers = dictionary["followers_count"] as? Int
        
    }
    
    func logout() {
        User.currentUser = nil
        TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
        
    //NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object: nil)
    }
    
    static let userDidLogoutNotification = "userDidLogout"
    
    class var currentUser: User? {
        
        get {
        if _currentUser == nil {
        //logged out or just boot up
        let data = NSUserDefaults.standardUserDefaults().objectForKey(currentUserKey) as? NSData
        if data != nil {
        let dictionary: NSDictionary?
        do {
        try dictionary = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
        _currentUser = User(dictionary: dictionary!)
    } catch {
        print(error)
        }
        }
        }
        return _currentUser
        }
        
        
        set(user) {
            _currentUser = user
            //User need to implement NSCoding; but, JSON also serialized by default
            if let _ = _currentUser {
                var data: NSData?
                do {
                    try data = NSJSONSerialization.dataWithJSONObject(user!.dictionary, options: .PrettyPrinted)
                    NSUserDefaults.standardUserDefaults().setObject(data, forKey: currentUserKey)
                } catch {
                    print(error)
                }
            } else {
                //Clear the currentUser data
                NSUserDefaults.standardUserDefaults().setObject(nil, forKey: currentUserKey)
            }
        }
    }
    
    
}