//
//  MAPageViewController.swift
//  MAPageViewController
//
//  Created by Mike on 6/19/14.
//  Copyright (c) 2014 Mike Amaral. All rights reserved.
//

import UIKit

class MAPageViewController: UIViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
  let pageViewController: UIPageViewController = UIPageViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)
  let pageControl: UIPageControl = UIPageControl()
  let pageControlHeight: CGFloat = 40
  var viewControllers: [UIViewController] = []
  var imageUrls: [String]?
  
  init(viewControllers: [UIViewController]) {
    self.viewControllers = viewControllers
    super.init(nibName: nil, bundle: nil)
  }
  
  override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
    super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
  }
  
  required init(coder: NSCoder) {
    fatalError("NSCoding not supported")
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    self.edgesForExtendedLayout = .None
    setupPageViewController()
  }
  
  func setupPageViewController() {
    
    pageViewController.delegate = self
    pageViewController.dataSource = self
    pageViewController.view.frame = self.view.frame
    pageViewController.setViewControllers([viewControllers[0]], direction: UIPageViewControllerNavigationDirection.Forward, animated: false, completion: nil)
    self.addChildViewController(pageViewController)
    self.view.addSubview(pageViewController.view)
    pageViewController.didMoveToParentViewController(self)
    
    pageControl.frame = CGRectMake(0, CGRectGetMaxY(self.view.frame) - pageControlHeight, self.view.bounds.size.width, pageControlHeight)
    pageControl.numberOfPages = viewControllers.count
    pageControl.autoresizingMask = [.FlexibleWidth, .FlexibleTopMargin]
    pageControl.userInteractionEnabled = true
    self.view.addSubview(pageControl)
    pageControl.addTarget(self, action: #selector(MAPageViewController.changePage(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    
  }
  
  // MARK : TO CHANGE WHILE CLICKING ON PAGE CONTROL
  func changePage(sender: UIPageControl) -> () {
    self.jumptoPage(sender.currentPage)
  }
  
  func indexOfViewController(viewController: UIViewController) -> Int {
    var indexOfVC: Int = 0
    for (index, element) in viewControllers.enumerate() {
      if element == viewController {
        indexOfVC = index
        break
      }
    }
    return indexOfVC
  }
  
  
  func jumptoPage(index : Int) {
    
    let vc = self.viewControllers[index]
    let direction : UIPageViewControllerNavigationDirection!
    
    if pageControl.currentPage < index {
      direction = UIPageViewControllerNavigationDirection.Forward
    }
    else {
      direction = UIPageViewControllerNavigationDirection.Reverse
    }
    
    if (pageControl.currentPage < index) {
      for var i = 0; i <= index; i += 1 {
        if (i == index) {
          self.pageViewController.setViewControllers([vc], direction: direction, animated: true, completion: nil)
        }
        else {
          self.pageViewController.setViewControllers([self.viewControllers[i]], direction: direction, animated: false, completion: nil)
        }
      }
    }
    else {
      for var i = pageControl.currentPage; i >= index; i = i - 1 {
        if i == index {
          self.pageViewController.setViewControllers([vc], direction: direction, animated: true, completion: nil)
        }
        else {
          self.pageViewController.setViewControllers([self.viewControllers[i]], direction: direction, animated: false, completion: nil)
        }
      }
    }
    pageControl.currentPage = index
  }
  
}

// UIPageViewControllerDataSource
extension MAPageViewController {
  
  func pageViewController(pageViewController: UIPageViewController, viewControllerAfterViewController viewController: UIViewController) -> UIViewController? {
    let indexOfCurrentVC = indexOfViewController(viewController)
    return indexOfCurrentVC < viewControllers.count - 1 ? viewControllers[indexOfCurrentVC + 1] : nil
  }
  
  func pageViewController(pageViewController: UIPageViewController, viewControllerBeforeViewController viewController: UIViewController) -> UIViewController?  {
    viewControllers.endIndex
    let indexOfCurrentVC = indexOfViewController(viewController)
    return indexOfCurrentVC > 0 ? viewControllers[indexOfCurrentVC - 1] : nil
  }
  
}

// UIPageViewControllerDelegate
extension MAPageViewController {
  func pageViewController(pageViewController: UIPageViewController, didFinishAnimating finished: Bool, previousViewControllers: [UIViewController], transitionCompleted completed: Bool) {
    if !completed {
      return
    }
    
    let newViewController = pageViewController.viewControllers![0]
    
    pageControl.currentPage = indexOfViewController(newViewController)
  }
  
}
