 import UIKit
 
 class RAMAnimatedTabBarItem: UITabBarItem {
-
-    @IBOutlet weak var animation: RAMItemAnimation?
-    @IBInspectable var textColor = UIColor.blackColor()
-
-    func playAnimation(icon: UIImageView, textLabel: UILabel){
-        guard let animation = animation else {
-            print("add animation in UITabBarItem")
-            return
-        }
-        animation.playAnimation(icon, textLabel: textLabel)
-    }
-
+    
+    @IBOutlet weak var animation: RAMItemAnimation!
+    @IBInspectable var textColor: UIColor = UIColor.blackColor()
+    
+    func playAnimation(icon: UIImageView, textLabel: UILabel) {
+        
+        assert(animation != nil, "add animation in UITabBarItem")
+        if animation != nil {
+            animation.playAnimation(icon, textLabel: textLabel)
+        }
+    }
+    
     func deselectAnimation(icon: UIImageView, textLabel: UILabel) {
-        animation?.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor)
-    }
-
+        if animation != nil {
+            animation.deselectAnimation(icon, textLabel: textLabel, defaultTextColor: textColor)
+        }
+    }
+    
     func selectedState(icon: UIImageView, textLabel: UILabel) {
-        animation?.selectedState(icon, textLabel: textLabel)
+        if animation != nil {
+            animation.selectedState(icon, textLabel: textLabel)
+        }
     }
 }
 
 class RAMAnimatedTabBarController: UITabBarController {
-
-    var iconsView: [(icon: UIImageView, textLabel: UILabel)] = []
-
-// MARK: life circle
-
+    
+    var iconsView: [(icon: UIImageView, textLabel: UILabel)] = Array()
+    
+    // MARK: life circle
+    
     override func viewDidLoad() {
         super.viewDidLoad()
-
+        
         let containers = createViewContainers()
-
+        
         createCustomIcons(containers)
-    }
-
-// MARK: create methods
-
-    func createCustomIcons(containers : [String: UIView]) {
-
-        if let items = tabBar.items as? [RAMAnimatedTabBarItem] {
-            
-            let itemsCount = items.count as Int - 1
-            
-            for (index, item) in items.enumerate() {
-
+        
+        
+    }
+    
+    // MARK: create methods
+    
+    func createCustomIcons(containers : NSDictionary) {
+        
+        if let _ = tabBar.items {
+            let itemsCount = tabBar.items!.count as Int - 1
+            var index = 0
+            for item in self.tabBar.items as! [RAMAnimatedTabBarItem] {
+                
                 assert(item.image != nil, "add image icon in UITabBarItem")
                 
-                guard let container = containers["container\(itemsCount-index)"] else
-                {
-                    print("No container given")
-                    continue
-                }
-                
+                let container : UIView = containers["container\(itemsCount-index)"] as! UIView
                 container.tag = index
-
+                
                 let icon = UIImageView(image: item.image)
                 icon.translatesAutoresizingMaskIntoConstraints = false
                 icon.tintColor = UIColor.clearColor()
-
+                
                 // text
                 let textLabel = UILabel()
                 textLabel.text = item.title

            multiplier: 1,
            constant: yOffset)
        container.addConstraint(constY)

        let constW = NSLayoutConstraint(item: view,
            attribute: NSLayoutAttribute.Width,
            relatedBy: NSLayoutRelation.Equal,

            constant: size.height)
        view.addConstraint(constH)
    }
    
    func createViewContainers() -> NSDictionary {
        
        var containersDict = [String: AnyObject]()
        let itemsCount : Int = tabBar.items!.count as Int - 1
        
        for index in 0...itemsCount {
            let viewContainer = createViewContainer()
            containersDict["container\(index)"] = viewContainer
        }
        
        //let keys = containersDict.keys
        
        var formatString = "H:|-(0)-[container0]"
        for index in 1...itemsCount {
            formatString += "-(0)-[container\(index)(==container0)]"
        }
        formatString += "-(0)-|"
        let  constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
            options:NSLayoutFormatOptions.DirectionRightToLeft,
            metrics: nil,
            views: (containersDict as [String : AnyObject]))
        view.addConstraints(constranints)
        
        return containersDict
    }
    
    func createViewContainer() -> UIView {
        let viewContainer = UIView();
        viewContainer.backgroundColor = UIColor.clearColor() // for test
        viewContainer.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(viewContainer)
        
        // add gesture
        let tapGesture = UITapGestureRecognizer(target: self, action: "tapHandler:")
        tapGesture.numberOfTouchesRequired = 1
        viewContainer.addGestureRecognizer(tapGesture)
        
        // add constrains
        let constY = NSLayoutConstraint(item: viewContainer,
            attribute: NSLayoutAttribute.Bottom,
            relatedBy: NSLayoutRelation.Equal,
            toItem: view,
            attribute: NSLayoutAttribute.Bottom,
            multiplier: 1,
            constant: 0)
        
        view.addConstraint(constY)
        
        let constH = NSLayoutConstraint(item: viewContainer,
            attribute: NSLayoutAttribute.Height,
            relatedBy: NSLayoutRelation.Equal,
            toItem: nil,
            attribute: NSLayoutAttribute.NotAnAttribute,
            multiplier: 1,
            constant: tabBar.frame.size.height)
        viewContainer.addConstraint(constH)
        
        return viewContainer
    }
    
    // MARK: actions
    
    func tapHandler(gesture:UIGestureRecognizer) {
        
        let items = tabBar.items as! [RAMAnimatedTabBarItem]
        
        let currentIndex = gesture.view!.tag
        if selectedIndex != currentIndex {
            let animationItem : RAMAnimatedTabBarItem = items[currentIndex]
            let icon = iconsView[currentIndex].icon
            let textLabel = iconsView[currentIndex].textLabel
            animationItem.playAnimation(icon, textLabel: textLabel)
            
            let deselelectIcon = iconsView[selectedIndex].icon
            let deselelectTextLabel = iconsView[selectedIndex].textLabel
            let deselectItem = items[selectedIndex]
            deselectItem.deselectAnimation(deselelectIcon, textLabel: deselelectTextLabel)
            
            selectedIndex = gesture.view!.tag
        }
    }
    
    func setSelectIndex(from from:Int,to:Int) {
        self.selectedIndex = to
        let items = self.tabBar.items as! [RAMAnimatedTabBarItem]
        items[from].deselectAnimation(iconsView[from].icon, textLabel: iconsView[from].textLabel)
        items[to].playAnimation(iconsView[to].icon, textLabel: iconsView[to].textLabel)
    }
}
