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

/*
 NOTES:
 
 need to display navigation bar so user can navigate back to previous screens if changes need to be made
 
 */

import UIKit
import SWRevealViewController

//@TODO: Need to make multiple images work for etsy and facebook and need to implement multiple images saving to firebase
class ListingPreviewViewController: UIViewController {
    
    //IBOutlets
    @IBOutlet weak var containerScrollView: UIScrollView!
    @IBOutlet weak var itemQuantity: UITextView!
    @IBOutlet weak var itemPicture: UIImageView!
    @IBOutlet weak var itemTitle: UITextView!
    @IBOutlet weak var itemDescription: UITextView!
    @IBOutlet weak var itemPrice: UITextView!
    @IBOutlet weak var itemCategory: UITextView!
    @IBOutlet weak var networks: UICollectionView!
    
    //class variables
    private var networksDictionary: Dictionary<String, Bool> = Dictionary<String, Bool>()
    private var graphManager: FacebookGraphAPIManager! = nil
    private var firManager: FirebaseManager! = nil
    private var ebayManager: EbayWebServiceManager! = nil
    private var etsyManager: EtsyRESTAPIManager! = nil
    private var itemListingDictionary: Dictionary<String, AnyObject>! = Dictionary<String, AnyObject>()
    private var alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert)
    private var lastListingKey: String!
    private var newInProgressListing: Dictionary<String,AnyObject> = Dictionary<String, AnyObject>()
    var loadingView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Do any additional setup after loading the view.
        
        // Initialization code
        self.networks.delegate = self
        self.networks.dataSource = self
        self.networks.backgroundView?.backgroundColor = UIColor.whiteColor()
        //self.graphManager.delegate = self
    }
    
    override func viewDidAppear(animated: Bool) {
        self.setListing()
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func setListing(){
        
        
        self.itemPicture.image = (self.itemListingDictionary["pictures"] as? [UIImageView])![0].image
        self.itemTitle.text = self.itemListingDictionary["title"] as! String
        self.itemDescription.text = self.itemListingDictionary["description"] as! String
        self.itemPrice.text = self.itemListingDictionary["price"] as! String
        self.itemCategory.text = self.itemListingDictionary["category"] as! String
        self.itemQuantity.text = self.itemListingDictionary["quantity"] as! String
    }
    
    func setDictionary(netdictionary:Dictionary<String, Bool>, itemdictionary: Dictionary<String, AnyObject!>){
        self.networksDictionary = netdictionary
        self.itemListingDictionary = itemdictionary
    }
    
    func setManagers(fbManager: FacebookGraphAPIManager, fireManager: FirebaseManager, ebayManager: EbayWebServiceManager, etsyManager: EtsyRESTAPIManager){
        self.graphManager = fbManager
        self.firManager = fireManager
        self.ebayManager = ebayManager
        self.etsyManager = etsyManager
    }
    
    
    
    // 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.
        
        if(segue.identifier == "EditListingSegue"){
            var imageData: [UIImage] = []
            for imageView in (self.itemListingDictionary["pictures"] as? [UIImageView])! {
                imageData.append(imageView.image!)
            }
            
            let dict: Dictionary<String, AnyObject> = ["title": self.itemTitle.text,
                                                       "description": self.itemDescription.text,
                                                       "price": self.itemPrice.text,
                                                       "quantity": self.itemQuantity.text,
                                                       "images": imageData,
                                                       "category": self.itemCategory.text,
                                                       "fbManager": self.graphManager,
                                                       "ebayManager": self.ebayManager,
                                                       "etsyManager": self.etsyManager,
                                                       "firebaseManager": self.firManager]
            let vc = (segue.destinationViewController as? ItemImagePickerViewController)!
            vc.toggleEditingMode(dict)
        }
    }
    
}

extension Dictionary {
    mutating func update(other:Dictionary) {
        for (key,value) in other {
            self.updateValue(value, forKey:key)
        }
    }
}
/*
 //MARK: - FacebookGraphAPIManagerDelegate methods
 extension ListingPreviewViewController: FacebookGraphAPIManagerDelegate {
 func listingUploadedFB(fbID: String) {
 
 self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").child(self.lastListingKey).updateChildValues(["network_listing_IDs":["fbID":fbID]])
 
 self.alert.title = "Listing Published"
 self.alert.message = "Your listing has been published to facebook"
 
 self.presentViewController(self.alert, animated: true, completion: nil)
 }
 }
 */

//MARK: - IBActions
extension ListingPreviewViewController {
    @IBAction func cancel(sender: AnyObject) {
        let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let vc = storyboard.instantiateViewControllerWithIdentifier("Reveal View Controller") as! SWRevealViewController
        self.presentViewController(vc, animated: true, completion: nil)
    }
    
    @IBAction func publishItem(sender: AnyObject) {
        self.loadingView = UIView(frame: self.view.frame)
        self.loadingView.backgroundColor = UIColor.grayColor()
        self.loadingView.alpha = 0.4
        
        self.firManager.indicator.center = self.view.center
        
        self.loadingView.addSubview(self.firManager.indicator)
        self.view.addSubview(loadingView)
        self.firManager.indicator.startAnimating()
        
        if(self.itemPicture.image == nil){
            let alert = UIAlertController(title: "Image Needed", message: "To proceed to choose networks, you must supply at least one picture for your listing", preferredStyle: .Alert)
            alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in alert.dismissViewControllerAnimated(true, completion: nil)}))
            
            self.presentViewController(alert, animated: true, completion: nil)
        }else{
            self.networksDictionary["areNetworksChosen"] = true
            
            //save listing to private user path in firebase
            let newListingRef = self.firManager.ref.child("Users").child("\(self.firManager.user_email)").child("user_Listings").childByAutoId()
            let postingGroup: dispatch_group_t = dispatch_group_create()
            
            
            //post to ebay
            if(self.networksDictionary["ebay"]!){
                dispatch_group_enter(postingGroup)
                
                let body: [String: String] = [ "title": self.itemTitle.text,
                                                  "quantity":self.itemQuantity.text,
                                                  "description":self.itemDescription.text,
                                                  "price":self.itemPrice.text,
                                                  "category_id":self.itemListingDictionary["ebaySubCategoryID"] as! String
                ]
                
                self.ebayManager.listItem(body, completion: {
                    (listingID, error) -> Void in
                        if((self.newInProgressListing["networkIDs"] == nil)){
                            self.newInProgressListing["networkIDs"] = Dictionary<String, AnyObject>()
                        }
                        var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary<String,    AnyObject>)
                        networkIDs["ebay"] = listingID as! String
                        self.newInProgressListing["networkIDs"] = networkIDs
                        dispatch_group_leave(postingGroup)
                })
            }
 
            
            //post to amazon
            if(self.networksDictionary["amazon"]!){
                
            }
            
            
            
            //post to etsy
            if(self.networksDictionary["etsy"]!){
                
                dispatch_group_enter(postingGroup)
                var categoryCode: Int!
                switch self.itemCategory.text {
                case "Accessories":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["accessories"] as! Int
                    break
                case "Art":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["art"] as! Int
                    break
                case "Bath, Beauty & Health":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["bath_and_beauty"] as! Int
                    break
                case "Bags & Purses":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["bags_and_purses"] as! Int
                    break
                case "Books":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["books_and_zines"] as! Int
                    break
                case "Candles":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["candles"] as! Int
                    break
                case "Ceramics & Pottery":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["ceramics_and_pottery"] as! Int
                    break
                case "Children":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["children"] as! Int
                    break
                case "Clothing & Shoes":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["clothing"] as! Int
                    break
                case "Crochet":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["crochet"] as! Int
                    break
                case "Dolls & Miniatures":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["dolls_and_miniatures"] as! Int
                    break
                case "Everything Else":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["everything_else"] as! Int
                    break
                case "Furniture":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["furniture"] as! Int
                    break
                case "Geekery":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["geekery"] as! Int
                    break
                case "Glass":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["glass"] as! Int
                    break
                case "Holidays":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["holidays"] as! Int
                    break
                case "Home/Houseware & Garden":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["housewares"] as! Int
                    break
                case "Jewelry & Watches":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["jewelry"] as! Int
                    break
                case "Knitting":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["knitting"] as! Int
                    break
                case "Music":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["music"] as! Int
                    break
                case "Needlecraft":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["needlecraft"] as! Int
                    break
                case "Paper Goods":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["paper_goods"] as! Int
                    break
                case "Patterns":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["patterns"] as! Int
                    break
                case "Plants and Edibles":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["plants_and_edibles"] as! Int
                    break
                case "Quilts":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["quilts"] as! Int
                    break
                case "Supplies":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["supplies"] as! Int
                    break
                case "Toys & Hobbies":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["toys"] as! Int
                    break
                case "Vintage":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["vintage"] as! Int
                    break
                case "Wedding":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["weddings"] as! Int
                    break
                case "Woodworking":
                    categoryCode = EtsyRESTAPIManager.settingsDictionary["categories"]!["woodworking"] as! Int
                    break
                default:
                    break
                }
                
                let body: [String: AnyObject] = [ "title": self.itemTitle.text,
                                                  "quantity":self.itemQuantity.text,
                                                  "description":self.itemDescription.text,
                                                  "price":self.itemPrice.text,
                                                  "category_id":categoryCode,
                                                  "who_made": EtsyRESTAPIManager.settingsDictionary["who_made"] as! String,
                                                  "is_supply": EtsyRESTAPIManager.settingsDictionary["is_supply"]!,
                                                  "when_made": EtsyRESTAPIManager.settingsDictionary["when_made"] as! String,
                                                  "shipping_template_id": EtsyRESTAPIManager.settingsDictionary["shipping_template_id"] as! Int,
                                                  "state":"draft"
                    
                ]
                
                self.etsyManager.sendPOSTRequest("/listings", body: body, onCompletion: {
                    (dict, error) -> Void in
                    
                    var results = (dict as! [[String : AnyObject]])[0]
                    
                    if((self.newInProgressListing["networkIDs"] == nil)){
                        self.newInProgressListing["networkIDs"] = Dictionary<String, AnyObject>()
                    }
                    var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary<String, AnyObject>)
                    networkIDs["etsy"] = results["listing_id"] as? Int
                    self.newInProgressListing["networkIDs"] = networkIDs
                    
                    let imageBody = ["listing_id": networkIDs["etsy"] as! Int,
                        //"type":"image/jpg",
                        "image": UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!]
                    
                    self.etsyManager.sendPOSTRequest(("listings/\(networkIDs["etsy"] as! Int)/images"), body: imageBody, onCompletion:  {
                        (dict, error) -> Void in
                        
                        dispatch_group_leave(postingGroup)
                    })
                    
                    
                })
                
            }
            
            
            //post to facebook
            if(self.networksDictionary["facebook"]!){
                dispatch_group_enter(postingGroup)
                
                let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(), isDirectory: true)
                let fileURL = tmpDirURL.URLByAppendingPathComponent("main").URLByAppendingPathExtension("jpg")
                print("FilePath: \(fileURL.path!)")
                do {
                    try UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!.writeToFile(fileURL.path!, options: NSDataWritingOptions.AtomicWrite)
                }catch{
                    (error)
                    print(error)
                }
                
                //let parameters: Dictionary<String, AnyObject> = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!)]
                
                let parameters: Dictionary<String, AnyObject> = ["Source": UIImageJPEGRepresentation(self.itemPicture.image!, 0.45)!, "published":false]
                
                self.lastListingKey = newListingRef.key
                self.graphManager.makePOSTResquest("me/photos", params: parameters, onComplete: {
                    (imageId, error) -> Void in
                    
                    var listingParams: Dictionary<String, AnyObject> = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!), "attached_media[0]":"{\"media_fbid\":\"\(imageId as! String)\"}"]
                    self.graphManager.makePOSTResquest("me/feed", params: listingParams, onComplete: {
                        (listingId, error) -> Void in
                        
                        if((self.newInProgressListing["networkIDs"] == nil)){
                            self.newInProgressListing["networkIDs"] = Dictionary<String, AnyObject>()
                        }
                        var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary<String, AnyObject>)
                        networkIDs["facebook"] = listingId as! String
                        self.newInProgressListing["networkIDs"] = networkIDs
                        dispatch_group_leave(postingGroup)

                    
                    })
                    /*
                     
                     */
                })
                
                //let parameters: Dictionary<String, AnyObject> = ["":""]
                
                
            }
            
            dispatch_group_notify(postingGroup, dispatch_get_main_queue(), {
                self.newInProgressListing.update(["listingID": newListingRef.key,
                    "seller email": (NSUserDefaults.standardUserDefaults().objectForKey("email") as? String)!,
                    "listingTitle": self.itemTitle.text,
                    "listingPrice": self.itemPrice.text,
                    "listingCategory": self.itemCategory.text,
                    "listingDescription": self.itemDescription.text,
                    "numberOfSupportingImages" : ((self.itemListingDictionary["pictures"] as? [UIImageView])?.count)! - 1,
                    "isListingDraft": false,
                    "networks": self.networksDictionary])
                
                
                self.firManager.ref.observeSingleEventOfType(.Value, withBlock: { snapshot in
                    
                    let databaseDict = snapshot.value as! [String : AnyObject]
                    
                    let storageRef = self.firManager.storage.referenceForURL((databaseDict["image_storage"] as? String)!)
                    
                    //change code to new multi-image saving
                    
                    
                    
                    let listingImageRef = storageRef.child("images/\(newListingRef.key)"+".jpg")
                    listingImageRef.putData(UIImageJPEGRepresentation(self.itemPicture.image!, 0.8)!, metadata: nil,completion:
                        {(metadata, error) -> Void in
                            
                            //for ebay due to its unique posting flow, will use firbase image storage url to add pictures
                            dispatch_group_enter(postingGroup)
                            if (self.networksDictionary["ebay"]!){
                                var networkIDs = self.newInProgressListing["networkIDs"] as! Dictionary<String, AnyObject>
                                
                                self.ebayManager.addImagesToListing(networkIDs["ebay"] as! String, imageURL: (metadata?.downloadURL()?.absoluteString)!, onCompletion: {
                                    (_, _) -> Void in
                                        dispatch_group_leave(postingGroup)
                                })
                            }else{
                                dispatch_group_leave(postingGroup)
                            }
                            
                            dispatch_group_notify(postingGroup, dispatch_get_main_queue(), {
                                newListingRef.setValue(self.newInProgressListing)
                                
                                // self.alert.title = "Listing saved with error"
                                // self.alert.message = "Your listing has been saved but something went wrong when trying to publish to facebook"
                                
                                
                                //let alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert)
                                
                                // self.alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in self.alert.dismissViewControllerAnimated(true, completion: nil)}))
                                
                                //register new listing id in global path of firebase root'
                                self.firManager.ref.child("Global_listings").child(newListingRef.key).setValue(newListingRef.key)
                                self.firManager.indicator.stopAnimating()
                                
                                let alert = UIAlertController(title: "Listing Posted Successfully", message: "Your listing was submitted to all networks successfully", preferredStyle: .Alert)
                                
                                alert.addAction(UIAlertAction(title: "OK", style: .Default, handler:{(action: UIAlertAction!) in
                                    
                                    self.cancel(self)
                                    alert.dismissViewControllerAnimated(true, completion: nil)
                                }))
                                
                                self.presentViewController(alert, animated: true, completion: nil)
                            })
                            
                            
                    })
                    
                    
                    
                    
                    
                })
            })
        }
        
        
    }
    
    @IBAction func editListing(sender: AnyObject) {
        
        self.performSegueWithIdentifier("EditListingSegue", sender: self)
    }
    
    
    
}

extension ListingPreviewViewController: UICollectionViewDelegate {
    
    /*
     // Uncomment this method to specify if the specified item should be highlighted during tracking
     override func collectionView(collectionView: UICollectionView, shouldHighlightItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
     }
     */
    
    /*
     // Uncomment this method to specify if the specified item should be selected
     override func collectionView(collectionView: UICollectionView, shouldSelectItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return true
     }
     */
    
    /*
     // Uncomment these methods to specify if an action menu should be displayed for the specified item, and react to actions performed on the item
     override func collectionView(collectionView: UICollectionView, shouldShowMenuForItemAtIndexPath indexPath: NSIndexPath) -> Bool {
     return false
     }
     
     override func collectionView(collectionView: UICollectionView, canPerformAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) -> Bool {
     return false
     }
     
     override func collectionView(collectionView: UICollectionView, performAction action: Selector, forItemAtIndexPath indexPath: NSIndexPath, withSender sender: AnyObject?) {
     
     }
     */
    
}

//Mark: - UICollectionViewDataSource methods
//need to dynamically show, hide, and rearrange the network cells based on users choice of networks
extension ListingPreviewViewController: UICollectionViewDataSource {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return 4
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell: UICollectionViewCell!
        
        switch (indexPath.row){
        case 0:
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("ebay", forIndexPath: indexPath)
            
            if(self.networksDictionary["ebay"] == false){
                cell.hidden = true
            }
            else{
                cell.hidden = false
            }
            break
            
        case 1:
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("amazon", forIndexPath: indexPath)
            
            if(self.networksDictionary["amazon"] == false){
                cell.hidden = true
            }
            else{
                cell.hidden = false
            }
            break
        case 2:
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("etsy", forIndexPath: indexPath)
            
            if(self.networksDictionary["etsy"] == false){
                cell.hidden = true
            }
            else{
                cell.hidden = false
            }
            break
        default:
            cell = collectionView.dequeueReusableCellWithReuseIdentifier("facebook", forIndexPath: indexPath)
            
            if(self.networksDictionary["facebook"] == false){
                cell.hidden = true
            }
            else{
                cell.hidden = false
            }
            break
        }
        
        
        return cell
    }
    
}

