//
//  ServiceNotificationManager.swift
//  Vendoo
//
//  Created by Okechi Onyeje on 8/30/16.
//  Copyright © 2016 Okechi Onyeje. All rights reserved.
//

import Foundation

protocol ServiceNotificationManagerDelegate {
    func listingHasEnded(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?)
    func listingHasNewNotifications(fbInfo: AnyObject?, ebayInfo: AnyObject?, amazonInfo: AnyObject?, etsyInfo: AnyObject?)
    func listingHasFinishedRetrievingNotifications()
    func listingHasStartedRetrievingNotifications()

}

class ServiceNotificationManager: NSObject {
    
    var etsyManager: EtsyRESTAPIManager!
    var fbGraphManager: FacebookGraphAPIManager!
    var firebaseManager: FirebaseManager!
    var ebayGraphManager: EbayWebServiceManager!
    var userListings: [Listing] = []
    var timer: NSTimer!
    static var delegate: ServiceNotificationManagerDelegate?
    
    override init() {
        super.init()
        
        
    }
    
    func startServicePolling() {
        timer = NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(ServiceNotificationManager.pollServices), userInfo: nil, repeats: true)
    }
    
    func stopServicePolling() {
        timer.invalidate()
    }
    
    func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager, etsyManager: EtsyRESTAPIManager){
        self.fbGraphManager = fbManager
        self.firebaseManager = fireManager
        self.ebayGraphManager = ebayManager
        self.etsyManager = etsyManager
    }
    
    func setListings(listings: [Listing]) {
        self.userListings = listings
    }
    
    func pollServices(){
        let notificationGroup = dispatch_group_create()
        for listing in userListings {
            
            self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(listing.key)").observeSingleEventOfType( .Value, withBlock: {
                (snapshot) -> Void in
                //dispatch_group_enter(notificationGroup)

                let listingDict = snapshot.value as? [String : AnyObject]
                
                if !(listingDict!["isListingDraft"] as! Bool) {
                    if let networksDict = listingDict!["networkIDs"] as? [String : AnyObject] {
                        let ebayID = (networksDict["ebay"] as? String)
                        let facebookID = (networksDict["facebook"] as? String)
                        let etsyID = (networksDict["etsy"] as? Int)
                        let amazonID = (networksDict["amazon"] as? String)

                        //@TODO: Skeleton for Notfications Manager is set up. Need to implement listing request for each listing to retrieve relevant notifications for user such as if listing has ended
                        if(ebayID != nil){
                            if self.ebayGraphManager.isAuthorized {
                                self.ebayGraphManager.isGettingNotification = true
                                self.ebayGraphManager.getListingInfo(ebayID!, onComplete: {
                                    (listingNotificationInfo, error) -> Void in
                                    //dispatch_group_leave(notificationGroup)
                                    let info = (listingNotificationInfo as! [String : AnyObject])
                                    if((info["quantitySold"] as! Int) > 0) {
                                        //@TODO: Add both firbase logic and code logic to do notifications for sold listings
                                    }
                                    if(info["status"] as! String == "Ended") {
                                        ServiceNotificationManager.delegate?.listingHasEnded(
                                            nil,
                                            ebayInfo: [
                                                "notification": "Your listing \"\(listingDict!["listingTitle"] as! String)\" has ended on ebay.",
                                                "listingKey": listing.key],
                                            amazonInfo: nil,
                                            etsyInfo: nil
                                        )

                                    }
                                    
                                })
                            }
                        }
                        if(facebookID != nil){
                            
                        }
                        if(etsyID != nil){
                            
                        }
                        if(amazonID != nil){
                            
                        }
                        //dispatch_group_leave(notificationGroup)
                    }else {
                       // dispatch_group_leave(notificationGroup)
                    }
                    
                    
                }else {
                    //dispatch_group_leave(notificationGroup)
                }
            })
        }
        self.ebayGraphManager.isGettingNotification = false

        
        //dispatch_group_notify(notificationGroup, dispatch_get_main_queue(), {
            //self.delegate?.listingHasNewNotifications(nil, ebayInfo: nil, amazonInfo: nil, etsyInfo: nil)
        //})
    
    }
    
}

