//
//  FeedPackagesCell.swift
//  kt
//
//  Created by neox on 16.08.17.
//  Copyright © 2017 SimpleCode. All rights reserved.
//

import UIKit

class FeedPackagesCell: UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate {
    
    @IBOutlet weak var collectionView: UICollectionView!
    
    var navController : UINavigationController?
    
    var feed : [FeedItem] = []
    
    override func awakeFromNib() {
        super.awakeFromNib()
        collectionView.delegate = self
        collectionView.dataSource = self
        requestDynamicMenu()
    }
    
    @IBAction func packagesPressed(sender: AnyObject) {
        let centerViewController = navController!.storyboard!.instantiateViewControllerWithIdentifier("ServiceMainViewController")
        let vc = self.navController?.parentViewController
        let rootVc = vc?.parentViewController
        if let pvc = rootVc as? RootVC {
            pvc.presentCenterViewController(centerViewController, animated: true)
        }
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return feed.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! FeedCollectionViewCell
        cell.image.imageFromServerURL(feed[indexPath.row].image!)
        cell.title.text = feed[indexPath.row].title
        cell.desc.text = feed[indexPath.row].desc
        cell.id = feed[indexPath.row].id
        cell.navController = self.navController
        return cell
    }
    
    func requestDynamicMenu() {
        if !DynamicMenuManager.sharedInstance().loaded {
            DynamicMenuManager.sharedInstance().getMenu({ error in
                if let error = error {
                    AlertViewUtil.showErrorAlert(LS("error"), message: error)
                } else {
                    DynamicMenuManager.sharedInstance().loaded = true
                    self.feed = DynamicMenuManager.sharedInstance().feed
                    self.collectionView.reloadData()
                }
            })
        } else {
            self.feed = DynamicMenuManager.sharedInstance().feed
            self.collectionView.reloadData()
        }
    }
}
