//
//  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] = []
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        dispatch_async(dispatch_get_main_queue(), {
            self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings").observeSingleEventOfType( .Value, withBlock: {
                (snapshot) -> Void in
                
                let listingDict = snapshot.value as? [String : AnyObject]
                if listingDict != nil {
                    dispatch_async(dispatch_get_main_queue(), {
                        
                        
                        
                        for (key, values) in listingDict! {
                            let serviceGroup: dispatch_group_t = dispatch_group_create()
                            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")
                                    }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)
                                                }
                                            })
                                            
                                        }
                                        
                                        
                                        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>)!
                                                ))
                                            
                                            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.
    }
    
    
}
