//
//  HomeViewController.swift
//  Vendoo
//
//  Created by Okechi Onyeje on 5/26/16.
//  Copyright © 2016 Okechi Onyeje. All rights reserved.
//

import UIKit

class HomeViewController: UITabBarController {
    //acts as RESTful api call manager for etsy
    //call this from tabbar controller to use etsy REST calls
    let etsyManager: EtsyRESTAPIManager = EtsyRESTAPIManager()
    let fbGraphManager = FacebookGraphAPIManager()
    let firebaseManager = FirebaseManager()
    let ebayGraphManager = EbayWebServiceManager()
    var userListings: [Listing] = []
    var notificationsManager = ServiceNotificationManager()
    var notifications: [Dictionary<String, String>] = (NSUserDefaults.standardUserDefaults().objectForKey("notifications") == nil ? [] : (NSUserDefaults.standardUserDefaults().objectForKey("notifications") as! [Dictionary<String, String>]))
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        ServiceNotificationManager.delegate = self
        self.notificationsManager.setManagers(fbGraphManager, fireManager: firebaseManager, ebayManager: ebayGraphManager, etsyManager: etsyManager)
        // Do any additional setup after loading the view.
        dispatch_async(dispatch_get_main_queue(), {
            
            //get all listing information for current user
            self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeSingleEventOfType( .Value, withBlock: {
                (snapshot) -> Void in
                
                let userDict = snapshot.value as? [String : AnyObject]
                
                let listingDict = userDict!["user_Listings"] as? [String : AnyObject]
                
                NSUserDefaults.standardUserDefaults().setObject(userDict!["name"] as? String, forKey: "name")
                
                if listingDict != nil {
                    var notificationStartTracker = 0
                    dispatch_async(dispatch_get_main_queue(), {
                        //let notificationStartGroup = dispatch_group_create()
                        for (key, values) in listingDict! {
                            let serviceGroup: dispatch_group_t = dispatch_group_create()
                            //dispatch_group_enter(notificationStartGroup)
                            self.firebaseManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
                                
                                let databaseDict = snapshot.value as! [String : AnyObject]
                                
                                let storageRef = self.firebaseManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
                                let mainListingImage = storageRef.child("images/\(key)/main.jpg")
                                
                                
                                dispatch_group_enter(serviceGroup)
                                mainListingImage.dataWithMaxSize(10 * 1024 * 1024, completion: {
                                    (dataMain, error) -> Void in
                                    
                                    if(error != nil){
                                        print("problem retrieving items")
                                        notificationStartTracker += 1
                                    }else{
                                        
                                        let mainImage = UIImage(data: dataMain!)
                                        var listingImages: [UIImage] = [mainImage!]
                                        var count = 0
                                        //Get supporting images
                                        for i in 2...5 {
                                            let supportListingImg1 = storageRef.child("images/\(key)/\(i).jpg")
                                            supportListingImg1.dataWithMaxSize(10 * 1024 * 1024, completion: {
                                                (data1, error) -> Void in
                                                
                                                if(error != nil){
                                                    print("support image \(i - 1) for key, \(key), does not exist")
                                                }else{
                                                    listingImages.append(UIImage(data: data1!)!)
                                                }
                                                print(key)
                                                count+=1
                                                if(count == 4){
                                                    dispatch_group_leave(serviceGroup)
                                                    notificationStartTracker += 1
                                                    //dispatch_group_enter(notificationStartGroup)
                                                    //dispatch_group_leave(notificationStartGroup)
                                                }
                                            })
                                            
                                        }
                                        
                                        
                                        dispatch_group_notify(serviceGroup, dispatch_get_main_queue(), {
                                            print(listingImages.count)
                                            let listingInfo = values as? [String : AnyObject]
                                            self.userListings.append(
                                                Listing(itemTitle: (listingInfo!["listingTitle"] as? String)!,
                                                    itemCategory: listingInfo!["listingCategory"] as? String,
                                                    itemPrice: listingInfo!["listingPrice"] as? String,
                                                    itemDescription: listingInfo!["listingDescription"] as? String,
                                                    itemImages: listingImages,
                                                    isDraftListing: (listingInfo!["isListingDraft"] as? Bool)!,
                                                    itemKey: key,
                                                    networksSellingOn: (listingInfo!["networks"] as? Dictionary<String, Bool>)!
                                                ))
                                            print(notificationStartTracker)
                                            if(notificationStartTracker == listingDict?.count){
                                                NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil)
                                                self.notificationsManager.setListings(self.userListings)
                                                self.notificationsManager.startServicePolling()
                                            }
                                            
                                            
                                            
                                        })
                                    
                                        
                                        
                                        
                                    }
                                })
                                
                                
                            })
                            
                            
                        }
                        /*
                        dispatch_group_notify(notificationStartGroup, dispatch_get_main_queue(), {
                            

                        })*/
                        
                        
                        
                    })
                }else {
                    NSNotificationCenter.defaultCenter().postNotificationName("finished_fetching_listings", object: nil)
                }
            
                
            })
        })
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    
    // MARK: - Navigation
    
    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    
    
}


extension HomeViewController: ServiceNotificationManagerDelegate {
    func listingHasFinishedRetrievingNotifications() {
        NSUserDefaults.standardUserDefaults().setObject(self.notifications, forKey: "notifications")
    }
    
    func listingHasStartedRetrievingNotifications() {
        
    }
    
    func listingHasEnded(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) {
        if (fbInfo != nil) {
            self.notifications.append(
                [
                    "network": "facebook",
                    "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                    "type": "ended",
                    "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                    "UUID": NSUUID().UUIDString
                ]
            )
        }
        
        if (ebayInfo != nil) {
            self.notifications.append(
                [
                "network": "ebay",
                "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                "type": "ended",
                "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                "UUID": NSUUID().UUIDString
                ]
            )
        }
        
        if (amazonInfo != nil) {
            self.notifications.append(
                [
                    "network": "amazon",
                    "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                    "type": "ended",
                    "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                    "UUID": NSUUID().UUIDString
                ]
            )
        }
        
        if (etsyInfo != nil) {
            self.notifications.append(
                [
                    "network": "etsy",
                    "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                    "type": "ended",
                    "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                    "UUID": NSUUID().UUIDString
                ]
            )
        }
        
    }
    
    func listingHasNewNotifications(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?) {
        
        
            if (fbInfo != nil) {
                self.notifications.append(
                    [
                        "network": "facebook",
                        "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                        "type": "ended",
                        "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                        "UUID": NSUUID().UUIDString
                    ]
                )
            }
            
            if (ebayInfo != nil) {
                self.notifications.append(
                    [
                        "network": "ebay",
                        "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                        "type": "ended",
                        "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                        "UUID": NSUUID().UUIDString
                    ]
                )
            }
            
            if (amazonInfo != nil) {
                self.notifications.append(
                    [
                        "network": "amazon",
                        "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                        "type": "ended",
                        "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                        "UUID": NSUUID().UUIDString
                    ]
                )
            }
            
            if (etsyInfo != nil) {
                self.notifications.append(
                    [
                        "network": "etsy",
                        "message": (ebayInfo as! [String : AnyObject])["notification"] as! String,
                        "type": "ended",
                        "key": (ebayInfo as! [String : AnyObject])["listingKey"] as! String,
                        "UUID": NSUUID().UUIDString
                    ]
                )
            }
        
    }
}
