//
//  HomeContentController.swift
//  kt
//
//  Created by Alexandr Zalutskiy on 16.01.15.
//  Copyright (c) 2015 Alexandr Zalutskiy. All rights reserved.
//

import UIKit

class HomeContentController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
  
  // MARK: UI
  
  @IBOutlet weak private var bottomView : UIView!
  @IBOutlet weak private var scrollView : UIScrollView!
  @IBOutlet weak private var pageControll : UIPageControl!
  
  // MARK: UI for localizable
  
  @IBOutlet weak private var packageButton : UIButton!
  @IBOutlet weak private var tvButton : UIButton!
  @IBOutlet weak private var internetButton : UIButton!
  @IBOutlet weak private var softwareButton : UIButton!
  @IBOutlet weak private var phoneButton : UIButton!
  @IBOutlet weak private var hostingButton : UIButton!
  @IBOutlet weak private var feedbackLabel: UILabel!
  @IBOutlet weak private var feedbackSubtitleLabel: UILabel!
  @IBOutlet weak private var pssLabel: UILabel!
  @IBOutlet weak private var pssSubtitleLabel: UILabel!
  
  // MARK: private logic
  
  private let facade = Facade.sharedInstance()
  private let notificationCenter = NSNotificationCenter.defaultCenter()
  private let bannersManager = BannersManager.sharedInstance()
  
  private var timer : NSTimer!
  
  private let bannersViewController = UIPageViewController(
    transitionStyle: .Scroll,
    navigationOrientation: .Horizontal,
    options: nil
  )
  
  private var banners: [Banner]?
  
  
  // MARK: View life cicle
  
  override func viewDidLoad() {
    registerForUpdateBunnres()
    Facade.sharedInstance().getBanners()
    
    bannersViewController.view.userInteractionEnabled = false
  }
  
  override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    
    localizable()
  }
  
  // MARK: Notification
  
  func registerForUpdateBunnres() {
    notificationCenter.addObserver(
      self,
      selector: #selector(HomeContentController.setBanners(_:)),
      name: BannersManagerUpdate,
      object: bannersManager
    )
  }
  
  // MARK: Observering
  
  func setBanners(notification: NSNotification) {
    let _banners = bannersManager.getBanners()
    
    banners = _banners
    
    bannersViewController.dataSource = self
    bannersViewController.delegate = self
    bannersViewController.view.frame = scrollView.frame
    pageControll.numberOfPages = banners!.count
    pageControll.currentPage = 0
    
    scrollView.addSubview(bannersViewController.view)
    addChildViewController(bannersViewController)
    
    if banners!.count != 0 {
      
      let vc = storyboard!.instantiateViewControllerWithIdentifier(BannerItemControllerId) as! BannerItemController
      vc.view.frame = scrollView.frame
      vc.banner = banners![0]
      
      bannersViewController.setViewControllers([vc], direction: .Forward, animated: true, completion: nil)
      
      bannersViewController.view.userInteractionEnabled = true
      
      timer = NSTimer.scheduledTimerWithTimeInterval(
        5,
        target: self,
        selector: #selector(HomeContentController.changeBanner(_:)),
        userInfo: nil,
        repeats: true
      )
    }
  }
  
  // MARK: UIPageViewControllerDataSource
  
  func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
    let id = viewController.view.tag
    let vc = storyboard!.instantiateViewControllerWithIdentifier(BannerItemControllerId) as! BannerItemController
    vc.view.frame = scrollView.frame
    if id + 1 != banners!.count {
      vc.banner = banners![id + 1]
      vc.view.tag = id + 1
    } else {
      vc.banner = banners![0]
      vc.view.tag = 0
    }
    return vc
  }
  
  func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController? {
    let id = viewController.view.tag
    let vc = storyboard!.instantiateViewControllerWithIdentifier(BannerItemControllerId) as! BannerItemController
    vc.view.frame = scrollView.frame
    if id != 0 {
      vc.banner = banners![id - 1]
      vc.view.tag = id - 1
    } else {
      vc.banner = banners![banners!.count - 1]
      vc.view.tag = banners!.count - 1
    }
    return vc
  }
  
  // MARK: UIPageViewControllerDelegate
  
  func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    pageControll.currentPage = pageViewController.viewControllers!.last!.view!.tag
  }
  
  // MARK: Helper fields
  
  var contentHeight : CGFloat {
    //        view.layoutSubviews()
    return bottomView.frame.maxY + 24.0
  }
  
  // MARK: Actions
  
  func changeBanner(sender: AnyObject) {
    if banners!.count != 0 {
      bannersViewController.setViewControllers(
        [pageViewController(
          bannersViewController,
          viewControllerAfterViewController: bannersViewController.viewControllers!.last! as UIViewController
          )!
        ],
        direction: .Forward,
        animated: true,
        completion: nil
      )
      pageControll.currentPage = bannersViewController.viewControllers!.last!.view!.tag
    }
  }
  
  @IBAction func packageButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Package)
  }
  
  @IBAction func tvButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Tv)
  }
  
  @IBAction func internetButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Internet)
  }
  
  @IBAction func softwareButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Software)
  }
  
  @IBAction func phoneButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Phone)
  }
  
  @IBAction func hostingButton_TouchUpInside(sender : UIButton) {
    showVCForService(.Hosting)
  }
  
  @IBAction func feedbackButton_TouchUpInside(sender : UIButton) {
    showVCWithName(FeedbackControllerId)
  }
  
  @IBAction func pssButton_TouchUpInside(sender : UIButton) {
    showVCWithName(PssControllerId)
  }
  
  // MARK: Helper
  
  private func localizable() {
    packageButton.setTitle(LocalizedString("menu.packets", description: "Пакеты").uppercaseString, forState: .Normal)
    tvButton.setTitle(LocalizedString("menu.tv", description: "Интернет").uppercaseString, forState: .Normal)
    internetButton.setTitle(LocalizedString("menu.internet", description: "Телевидение").uppercaseString, forState: .Normal)
    softwareButton.setTitle(LocalizedString("menu.rent", description: "Аренда ПО").uppercaseString, forState: .Normal)
    phoneButton.setTitle(LocalizedString("menu.telephony", description: "Телефония").uppercaseString, forState: .Normal)
    hostingButton.setTitle(LocalizedString("menu.hosting", description: "Хостинг").uppercaseString, forState: .Normal)
    
    feedbackLabel.text = LocalizedString("menu.feedback", description: "Звонки в службу поддержки")
    feedbackSubtitleLabel.text = LocalizedString("main.feedback_button.support_service_calls", description: "Обратная связь")
    
    pssLabel.text = LocalizedString("menu.service-points", description: "Пункты сети сервиса")
    pssSubtitleLabel.text = LocalizedString("main.pss_button.points_on_your_city_map", description: "Отметки на карте вашего города")
  }
  
  private func getServiceController() -> ServiceNavigationController {
    return getVCWithName(ServiceControllerId) as! ServiceNavigationController
  }
  
  private func showVCForService(service: Service) {
    let rootViewController = parentViewController!.navigationController!.parentViewController!
      as? RootViewController
    let vc = getServiceController()
    vc.service = service
    rootViewController?.presentCenterViewController(vc, animated: true)
  }
  
  private func showVCWithName(name : String) {
    let rootViewController = parentViewController!.navigationController!.parentViewController!
      as? RootViewController
    let vc = getVCWithName(name)
    rootViewController?.presentCenterViewController(vc, animated: true)
  }
  
  private func getVCWithName(name : String) -> UIViewController! {
    return self.storyboard!.instantiateViewControllerWithIdentifier(name)
  }
}
