//
//  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!
    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: - 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.
    }
}

// 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
        return ((self.tabBarController as? HomeViewController)?.userListings.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
        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{
            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
                }
                if(!((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["amazon"])!){
                    cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 1, inSection: 0))?.hidden = true
                }
                if(!((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["etsy"])!){
                    cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 2, inSection: 0))?.hidden = true
                    
                }
                if(!((self.tabBarController as? HomeViewController)!.userListings[indexPath.row].networks["facebook"])!){
                    cell.networks.cellForItemAtIndexPath(NSIndexPath(forRow: 3, inSection: 0))?.hidden = true
                }

            })
            
        }
        return cell
    }
}


//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
     }
     */
}


