// // 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 //@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 = Dictionary() private var graphManager: FacebookGraphAPIManager! = nil private var firManager: FirebaseManager! = nil private var ebayManager: EbayWebServiceManager! = nil private var etsyManager: EtsyRESTAPIManager! = nil private var itemListingDictionary: Dictionary! = Dictionary() private var alert = UIAlertController(title: "Listing Published", message: "Your listing has been published", preferredStyle: .Alert) private var lastListingKey: String! private var newInProgressListing: Dictionary = Dictionary() 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, itemdictionary: Dictionary){ 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"){ let vc = (segue.destinationViewController as? ItemImagePickerViewController)! vc.itemName.text? = self.itemTitle.text vc.itemPrice.text? = self.itemPrice.text vc.itemDescription.text? = self.itemDescription.text vc.possibleItemImageMain = self.itemPicture vc.itemQuantity.text? = self.itemQuantity.text } } } 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 publishItem(sender: AnyObject) { 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) var categoryCode: String! var dict = EbayWebServiceManager.settingsDictionary["categories"]! switch self.itemCategory.text { case "Antiques": categoryCode = dict["Antiques"] as! String break case "Art": categoryCode = dict["Art"] as! String break case "Baby": categoryCode = dict["Baby"] as! String break case "Bath, Beauty & Health": categoryCode = dict["Health and Beauty"] as! String break case "Books": categoryCode = dict["Books"] as! String break case "Business & Industrial": categoryCode = dict["Business and Industrial"] as! String break case "Cameras & Photo": categoryCode = dict["Cameras and Photo"] as! String break case "Cell Phones & Accessories": categoryCode = dict["Cell Phones and Accessories"] as! String break case "Clothing & Shoes": categoryCode = dict["Clothing, Shoes and Accessories"] as! String break case "Coins & Paper Money": categoryCode = dict["Coins and Paper Money"] as! String break case "Collectibles": categoryCode = dict["Collectibles"] as! String break case "Computers/Tablets and Networking": categoryCode = dict["Computers/Tablets and Networking"] as! String break case "Consumer Electronics": categoryCode = dict["Consumer Electronics"] as! String break case "Crafts": categoryCode = dict["Crafts"] as! String break case "Dolls & Miniatures": categoryCode = dict["Dolls and Bears"] as! String break case "DVDs & Movies": categoryCode = dict["DVDs & Movies"] as! String break case "Entertainment Memorabilia": categoryCode = dict["Entertainment Memorabilia"] as! String break case "Everything Else": categoryCode = dict["Everything Else"] as! String break case "Gift Cards & Coupons": categoryCode = dict["Gift Cards and Coupons"] as! String break case "Home/Houseware & Garden": categoryCode = dict["Coins and Paper Money"] as! String break case "Jewelry & Watches": categoryCode = dict["Jewelry and Watches"] as! String break case "Musical Instruments & Gear": categoryCode = dict["Musical Instruments and Gear"] as! String break case "Pet Supplies": categoryCode = dict["Pet Supplies"] as! String break case "Pottery & Glass": categoryCode = dict["Pottery and Glass"] as! String break case "Real Estate": categoryCode = dict["Real Estate"] as! String break case "Specialty Services": categoryCode = dict["Specialty Services"] as! String break case "Sporting Goods": categoryCode = dict["Sporting Goods"] as! String break case "Sports Memorabilia & Fan Shop": categoryCode = dict["Sports Mem, Cards and Fan Shop"] as! String break case "Tickets & Experiences": categoryCode = dict["Tickets and Experiences"] as! String break case "Toys & Hobbies": categoryCode = dict["Toys and Hobbies"] as! String break case "Travel": categoryCode = dict["Travel"] as! String break case "Video Games & Consoles": categoryCode = dict["Video Games and Consoles"] as! String break default: break } let body: [String: String] = [ "title": self.itemTitle.text, "quantity":self.itemQuantity.text, "description":self.itemDescription.text, "price":self.itemPrice.text, "category_id":categoryCode ] self.ebayManager.listItem(body) } //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() } var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary) 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 = ["message":("**"+self.itemTitle.text!+"**\n\n"+"Price: "+self.itemPrice.text! + "\n\n"+self.itemDescription.text!)] let parameters: Dictionary = ["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 = ["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() } var networkIDs = (self.newInProgressListing["networkIDs"] as! Dictionary) networkIDs["facebook"] = listingId as! String self.newInProgressListing["networkIDs"] = networkIDs dispatch_group_leave(postingGroup) }) /* */ }) //let parameters: Dictionary = ["":""] } 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 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) }) }) }) } } @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 } }