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

/*
 This class will be used to retrieve and manipulate data seen by the end user for he/she's item listings
 */
import UIKit
import TYMActivityIndicatorView

class ItemTableViewController: UIViewController {

    //outlet
    @IBOutlet weak var itemTable: UITableView!
    @IBOutlet weak var tableSegmentController: UISegmentedControl!
    
    @IBOutlet weak var menuButton: UIBarButtonItem!
    
    var loadingView: UIView!
    var selectedListing: Listing!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        
        self.tabBarController?.tabBar.hidden = false
        
        //set delegates
        self.itemTable.dataSource = self
        self.itemTable.delegate = self
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(stopIndicator), name: "finished_fetching_listings", object: nil)
        if self.revealViewController() != nil {
            menuButton.target = self.revealViewController()
            menuButton.action = "revealToggle:"
            self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
        }
        
        self.loadingView = UIView(frame: self.view.frame)
        self.loadingView.backgroundColor = UIColor.grayColor()
        self.loadingView.alpha = 0.4
        ((self.tabBarController as? HomeViewController)?.firebaseManager.indicator)!.center = self.view.center

        
        self.loadingView.addSubview(((self.tabBarController as? HomeViewController)?.firebaseManager.indicator)!)
        self.view.addSubview(loadingView)
        (self.tabBarController as? HomeViewController)?.firebaseManager.indicator.startAnimating()
        
        
    }

    
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = false
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    
    func stopIndicator(){
        (self.tabBarController as? HomeViewController)?.firebaseManager.indicator.stopAnimating()
        self.loadingView.removeFromSuperview()
        self.itemTable.reloadData()
    }
   

    /*
    
    */

}

// MARK: - IBAction
extension ItemTableViewController {
    @IBAction func segSwitch(sender: UISegmentedControl) {
        self.itemTable.reloadData()
    }
}

// MARK: - Navigation
extension ItemTableViewController {
    
    // 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.
        
        let des = segue.destinationViewController as! ListingPreviewViewController
        var tempImages: [UIImageView] = []
        for uiImage in self.selectedListing.images {
            tempImages.append(UIImageView(image: uiImage))
        }
        let dict:[String:AnyObject] = [
            "pictures": tempImages,
            "title": self.selectedListing.title != nil ? self.selectedListing.title : "",
            "description": self.selectedListing.desc != nil ? self.selectedListing.desc: "",
            "price": self.selectedListing.price != nil ? self.selectedListing.price : "",
            "category": self.selectedListing.category != nil ? self.selectedListing.category : "",
            "quantity": self.selectedListing.quantity != nil ? self.selectedListing.quantity: nil
        ]
        
        des.setDictionary(self.selectedListing.networks, itemdictionary: dict)
        des.setManagers(
            ((self.tabBarController as? HomeViewController)?.fbGraphManager)!,
            fireManager: ((self.tabBarController as? HomeViewController)?.firebaseManager)!,
            ebayManager: ((self.tabBarController as? HomeViewController)?.ebayGraphManager)!,
            etsyManager: ((self.tabBarController as? HomeViewController)?.etsyManager)!
        )
                
        if self.selectedListing.isDraft! {
            des.setViewState("Editible")
        }else {
            des.setViewState("NonEditable")
        }
        
    }
}

// MARK: - TableView Datasource methods
extension ItemTableViewController: UITableViewDataSource{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        if self.tableSegmentController.selectedSegmentIndex == 0 {
            return ((self.tabBarController as? HomeViewController)?.userListings.count)!
        }
        else if tableSegmentController.selectedSegmentIndex == 1 {
            return ((self.tabBarController as? HomeViewController)?.endedListings.count)!
        }
        else{
            return ((self.tabBarController as? HomeViewController)?.soldListings.count)!
        }
        
        
    }
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell: ItemCell! = (tableView.dequeueReusableCellWithIdentifier("Item Cell", forIndexPath: indexPath) as! ItemCell)
        
        // Configure the cell...
        //for each listing cell generated need to find the marketplaces it belongs to, the listing price, the name of the item, the status of the item, and the item image.
        //Once these objects are retrieved, access the ItemCell properties and manipulate as needed
        
        if self.tableSegmentController.selectedSegmentIndex == 0 {
            cell.itemImage.image = (self.tabBarController as? HomeViewController)?.userListings[indexPath.row].images[0] //come back
            cell.itemName.text = (self.tabBarController as? HomeViewController)!.userListings[indexPath.row].title
            cell.itemPrice.text = (self.tabBarController as? HomeViewController)!.userListings[indexPath.row].price
            
            //check if item is published
            if((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].isDraft!){
                cell.itemStatus.text = "Status: Unpublished"
                dispatch_async(dispatch_get_main_queue(), {
                    
                    cell.alpha = 0.5
                    
                    
                })
                
            }else {
                cell.itemStatus.text = "Status: Active"
            }
            
            if(!((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["areNetworksChosen"])!){
                cell.networks.hidden = true
            }else{
                cell.selectedNetworks = []
                dispatch_async(dispatch_get_main_queue(), {
                    if(((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["ebay"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true
                        cell.addNetwork("ebay_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["amazon"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true
                        cell.addNetwork("amazon_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["etsy"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true
                        cell.addNetwork("etsy_icon")
                        
                    }
                    if(((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["facebook"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = true
                        cell.addNetwork("facebook_icon")
                    }
                    cell.networks.reloadData()
                    
                })
                
            }

        }
        else if tableSegmentController.selectedSegmentIndex == 1 {
            cell.itemImage.image = (self.tabBarController as? HomeViewController)?.endedListings[indexPath.row].images[0] //come back
            cell.itemName.text = (self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].title
            cell.itemPrice.text = (self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].price
            
            cell.itemStatus.text = "Status: Unsold"
                
            if(!((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["areNetworksChosen"])!){
                cell.networks.hidden = true
            }else{
                cell.selectedNetworks = []
                dispatch_async(dispatch_get_main_queue(), {
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["ebay"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true
                        cell.addNetwork("ebay_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["amazon"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true
                        cell.addNetwork("amazon_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["etsy"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true
                        cell.addNetwork("etsy_icon")
                        
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["facebook"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = true
                        cell.addNetwork("facebook_icon")
                    }
                    cell.networks.reloadData()
                })
                
            }

        }
        else{
            cell.itemImage.image = (self.tabBarController as? HomeViewController)?.soldListings[indexPath.row].images[0] //come back
            cell.itemName.text = (self.tabBarController as? HomeViewController)!.soldListings[indexPath.row].title
            cell.itemPrice.text = (self.tabBarController as? HomeViewController)!.soldListings[indexPath.row].price
            
            cell.itemStatus.text = "Status: Sold"
            
            if(!((self.tabBarController as? HomeViewController)!.soldListings[indexPath.row].networks["areNetworksChosen"])!){
                cell.networks.hidden = true
            }else{
                cell.selectedNetworks = []
                dispatch_async(dispatch_get_main_queue(), {
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["ebay"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))?.hidden = true
                        cell.addNetwork("ebay_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["amazon"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true
                        cell.addNetwork("amazon_icon")
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["etsy"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true
                        cell.addNetwork("etsy_icon")
                        
                    }
                    if(((self.tabBarController as? HomeViewController)!.endedListings[indexPath.row].networks["facebook"])!){
                        //cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = true
                        cell.addNetwork("facebook_icon")
                    }
                    cell.networks.reloadData()
                })
                
            }
        }
        
        
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if self.tableSegmentController.selectedSegmentIndex == 0 {
            self.selectedListing = (self.tabBarController as? HomeViewController)?.userListings[indexPath.row]
        }
        else if tableSegmentController.selectedSegmentIndex == 1 {
            self.selectedListing = (self.tabBarController as? HomeViewController)?.endedListings[indexPath.row]
        }
        else{
            self.selectedListing = (self.tabBarController as? HomeViewController)?.soldListings[indexPath.row]
        }
        self.performSegueWithIdentifier("ItemDetailSegue", sender: self)
    }
}


//MARK: - Tableview Delegate Methods
extension ItemTableViewController: UITableViewDelegate {
    /*
     // Override to support conditional editing of the table view.
     override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     // Return false if you do not want the specified item to be editable.
     return true
     }
     */
    
    /*
     // Override to support editing the table view.
     override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
     if editingStyle == .Delete {
     // Delete the row from the data source
     tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
     } else if editingStyle == .Insert {
     // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
     }
     }
     */
    
    /*
     // Override to support rearranging the table view.
     override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
     
     }
     */
    
    /*
     // Override to support conditional rearranging of the table view.
     override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
     // Return false if you do not want the item to be re-orderable.
     return true
     }
     */
}


