//
//  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(60.0, target: self, selector: #selector(ServiceNotificationManager.pollServices), userInfo: nil, repeats: true)
        pollServices()
    }
    
    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()
        //let notificationEndCount = 0
        //dispatch_group_enter(notificationGroup)
        for listing in userListings {
            
            self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)/user_Listings/\(listing.key)").observeSingleEventOfType( .Value, withBlock: {
                (snapshot) -> Void in
                

                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.getListingInfo(ebayID!, onComplete: {
                                    (listingNotificationInfo, error) -> Void in
                                    //dispatch_group_leave(notificationGroup)
                                    let info = (listingNotificationInfo as! [String : AnyObject])
                                    if(info["status"] as! String == "Ended") {
                                        if((info["quantitySold"] as! Int) > 0) {
                                            //@TODO: Add both firbase logic and code logic to do notifications for sold listings
                                            if (((info["itemQuantity"] as! Int) - (info["quantitySold"] as! Int)) == 0) {
                                                
                                                ServiceNotificationManager.delegate?.listingHasNewNotifications(
                                                    nil,
                                                    ebayInfo: [
                                                        "type": "Sold",
                                                        "notification": "Your listing \"\(listingDict!["listingTitle"] as! String)\" has sold out on ebay.",
                                                        "listingKey": listing.key],
                                                    amazonInfo: nil,
                                                    etsyInfo: nil
                                                )
                                            }
                                        }else{
                                            ServiceNotificationManager.delegate?.listingHasEnded(
                                                nil,
                                                ebayInfo: [
                                                    "type": "Ended",
                                                    "notification": "Your listing \"\(listingDict!["listingTitle"] as! String)\" has ended on ebay.",
                                                    "listingKey": listing.key],
                                                amazonInfo: nil,
                                                etsyInfo: nil
                                            )
                                        }
                                        

                                    }
                                    
                                })
                            }
                        }
                        if(facebookID != nil){
                            if(self.fbGraphManager.isAuthorized) {
                                self.fbGraphManager.getListingInfo ("/\(facebookID!)/comments", onCompletion: {
                                    (listingNotificationInfo, error) -> Void in
                                    
                                    dispatch_async(dispatch_get_main_queue(), {
                                        self.firebaseManager.ref.child("Users/\(self.firebaseManager.user_email)").observeEventType(.Value, withBlock: {
                                            (snapshot) -> Void in
                                            
                                            let notifications = ((snapshot.value as? [String : AnyObject])!["notifications"]) as? [String : AnyObject]
                                            
                                            
                                                for commentInfo in (listingNotificationInfo as! [[String: AnyObject]]) {
                                                    let fromInfo = commentInfo["from"] as! [String : AnyObject]
                                                    if notifications != nil {
                                                        if notifications![(commentInfo["id"] as! String)] == nil {
                                                            let commentDict = [
                                                                "UUID":(commentInfo["id"] as! String),
                                                                "commentMessage":(commentInfo["message"] as! String),
                                                                "network":"facebook",
                                                                "notification": "Your item \"\(listingDict!["listingTitle"] as! String)\" has a new comment.",
                                                                "key": listing.key,
                                                                "seen":false,
                                                                "senderID":(fromInfo["id"]! as! String),
                                                                "senderName":(fromInfo["name"]! as! String),
                                                                "type":"FBComment"
                                                            ]
                                                            ServiceNotificationManager.delegate?.listingHasNewNotifications(commentDict, ebayInfo: nil, amazonInfo: nil, etsyInfo: nil)
                                                        }

                                                    }else{
                                                        let commentDict = [
                                                            "UUID":(commentInfo["id"] as! String),
                                                            "commentMessage":(commentInfo["message"] as! String),
                                                            "network":"facebook",
                                                            "notification": "Your item \"\(listingDict!["listingTitle"] as! String)\" has a new comment.",
                                                            "key": listing.key,
                                                            "seen":false,
                                                            "senderID":(fromInfo["id"]! as! String),
                                                            "senderName":(fromInfo["name"]! as! String),
                                                            "type":"FBComment"
                                                        ]
                                                        ServiceNotificationManager.delegate?.listingHasNewNotifications(commentDict, ebayInfo: nil, amazonInfo: nil, etsyInfo: nil)
                                                    }
                                                    
                                                }
                                            
                                            
                                        })
                                    })
                                    
                            })
                                
                            }
                        }
                        if(etsyID != nil){
                            if (self.etsyManager.isAuthorized) {
                                self.etsyManager.getListingInfo ("/listings/\(etsyID!)", onCompletion: {
                                    (listingNotificationInfo, error) -> Void in
                                    
                                    let info = (listingNotificationInfo as! [String : AnyObject])
                                    
                                    //@TODO: Test this code with the draft condition for both expired and sold_out
                                    if ((info["status"] as! String == "expired") || (info["status"] as! String == "removed")) {
                                        
                                        ServiceNotificationManager.delegate?.listingHasEnded(
                                            nil,
                                            ebayInfo: nil,
                                            amazonInfo: nil,
                                            etsyInfo: [
                                                "type": "Ended",
                                                "notification": "Your listing \"\(listingDict!["listingTitle"] as! String)\" has ended on etsy.",
                                                "listingKey": listing.key]
                                        )

                                    
                                    }else if info["status"] as! String == "sold_out" {
                                        
                                        ServiceNotificationManager.delegate?.listingHasNewNotifications(
                                            nil,
                                            ebayInfo: nil,
                                            amazonInfo: nil,
                                            etsyInfo: [
                                                "type": "Sold",
                                                "notification": "Your listing \"\(listingDict!["listingTitle"] as! String)\" has sold out on etsy.",
                                                "listingKey": listing.key]
                                        )
                                        
                                    } else if info["status"] as! String == "draft" {
                                    
                                    }
                                
                            })
                            
                            }
                        }
                        if(amazonID != nil){
                            
                        }
                        //dispatch_group_leave(notificationGroup)
                    }else {
                       // dispatch_group_leave(notificationGroup)
                    }
                    
                    
                }else {
                    //dispatch_group_leave(notificationGroup)
                }
            })
        }

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

