//
//  ModalWindow.swift
//  kt
//
//  Created by Assylkhan Rakhatov on 01.02.16.
//  Copyright © 2016 Alexandr Zalutskiy. All rights reserved.
//

import Foundation
import UIKit

func showModally(presentedVC: UIViewController, presentingVC: UIViewController, width: CGFloat, height: CGFloat, cornerRadius: CGFloat? = nil) {
  //  let helpVC = presentingVC.storyboard?.instantiateViewControllerWithIdentifier("help") as! HelpViewController
  if let cornerRadius = cornerRadius {
    presentedVC.view.layer.cornerRadius = cornerRadius
  }
  presentingVC.addChildViewController(presentedVC)
  ModalWindow.sharedInstance().showLoadingView(presentingVC, vc: presentedVC, viewHeight: height, viewWidth: width)
}

class ModalWindow {
  var loadingView: UIView!
  static var instance: ModalWindow!
  var presentedVC: UIViewController?
  
  static func sharedInstance() -> ModalWindow {
    if instance == nil {
      instance = ModalWindow()
    }
    return instance
  }
  
  private func createLoadingView(parentVC: UIViewController, vc: UIViewController, viewHeight: CGFloat, viewWidth: CGFloat) {
    presentedVC = vc
    loadingView = UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: parentVC.view.frame.width, height: parentVC.view.frame.height)))
    loadingView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
    
    let viewX = (CGFloat(CGRectGetWidth(UIScreen.mainScreen().bounds)) - viewWidth) / 2.0
    let viewY = (CGFloat(CGRectGetHeight(UIScreen.mainScreen().bounds)) - viewHeight) / 2.4
    let v = vc.view
    v.frame = CGRectMake(viewX, viewY, viewWidth, viewHeight)
    loadingView.addSubview(v)
  }
  
  func showLoadingView(parentVC: UIViewController, vc: UIViewController, viewHeight: CGFloat, viewWidth: CGFloat) {
    createLoadingView(parentVC, vc: vc, viewHeight: viewHeight, viewWidth: viewWidth)
    UIView.animateWithDuration(0.5, animations: { () -> Void in
      self.loadingView.alpha = 1}) { (finished) -> Void in
        parentVC.view.addSubview(self.loadingView)
    }
  }
  
  func hideLoadingView(completion: (()-> Void)? = nil) {
    UIView.animateWithDuration(0.3, animations: {
      self.loadingView.alpha = 0.0}, completion: { (done: Bool) -> Void in
        if let nav = self.presentedVC?.parentViewController as? UINavigationController {
          var viewControllers = nav.viewControllers
          if let presentedVC = self.presentedVC {
            viewControllers.removeItem(presentedVC)
          }
          nav.viewControllers = viewControllers
//          self.loadingView.removeFromSuperview()
        } else {
          self.presentedVC?.removeFromParentViewController()
          self.loadingView.removeFromSuperview()
        }
        completion?()
    })
    NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)
  }
  
}
