 import SnapKit
 import WebImage
 
+private let URLToImageView: NSURL -> UIImageView = { URL -> UIImageView in
+    let view = UIImageView()
+    view.sd_setImageWithURL(URL)
+    return view
+}
+
 extension TDPagedImageScrollView {
-    public func configureWithImages(images: [UIImage]) {
-        let views = images.map { return UIImageView(image: $0) }
+    public func configureWithImages(images: [UIImage], infiniteLoop: Bool = false) {
+        self.infiniteLoop = infiniteLoop
+
+        var views = images.map { return UIImageView(image: $0) }
+
         configureWithViews(views)
     }
 
-    public func configureWithImageURLs(imageURLs: [NSURL]) {
-        let views = imageURLs.map { URL -> UIImageView in
-            let view = UIImageView()
-            view.sd_setImageWithURL(URL)
-            return view
-        }
+    public func configureWithImageURLs(imageURLs: [NSURL], infiniteLoop: Bool = false) {
+        self.infiniteLoop = infiniteLoop
+
+        var views = imageURLs.map(URLToImageView)
+
         configureWithViews(views)
     }
 
-    internal func configureWithViews(views: [UIView]) {
+    internal func configureWithViews(var views: [UIView]) {
         clearSubviewsInScrollView()
 
         let superView = containerView

extension TDPagedImageScrollView: UIScrollViewDelegate {
    public func scrollViewDidScroll(scrollView: UIScrollView) {
        let pageWidth = scrollView.frame.size.width
        let xOffsetRelativeToPageWidth = scrollView.contentOffset.x/pageWidth

        // Update when scrolling to more than 50% of the previous/next page
        pageControl.currentPage = Int(floor(xOffsetRelativeToPageWidth + 0.5))
    }
}

extension TDPagedImageScrollView {
    internal func configureWithColoredViews() {
        let colors: [UIColor] = [
            .blackColor(),
            .whiteColor(),
            .blackColor(),
            .grayColor(),
            .blackColor(),
        ]

        let views = map(colors) { color -> UIView in
            let view = UIView()
            view.backgroundColor = color
            return view
        }

        configureWithViews(views)

}

public class TDPagedImageScrollView: UIView {
    public var infiniteLoop = false

    // MARK: UI vars
    public lazy var scrollView: UIScrollView = {
        let scrollView = UIScrollView()
