//
//  LargeImageInteractionController.swift
//  Tusker
//
//  Created by Shadowfacts on 9/1/18.
//  Copyright © 2018 Shadowfacts. All rights reserved.
//

import UIKit

class LargeImageInteractionController: UIPercentDrivenInteractiveTransition {
    
    var inProgress = false
    var direction: CGFloat?
    
    var shouldCompleteTransition = false
    private weak var viewController: LargeImageAnimatableViewController!
    
    init(viewController: LargeImageAnimatableViewController) {
        super.init()
        self.viewController = viewController
        let panRecognizer = UIPanGestureRecognizer(target: self, action: #selector(handleGesture(_:)))
        panRecognizer.allowedScrollTypesMask = .continuous
        viewController.view.addGestureRecognizer(panRecognizer)
    }
    
    @objc func handleGesture(_ recognizer: UIPanGestureRecognizer) {
        guard let recognizerSuperview = recognizer.view?.superview else {
            // Assume the gesture has ended b/c we don't have a view/superview anymore.
            inProgress = false
            direction = nil
            cancel()
            return
        }
        let translation = recognizer.translation(in: recognizerSuperview)
        var progress = translation.y / 200
        if let direction = direction {
            progress *= direction
        } else if abs(progress) > 0.01 {
            // if the progress is less than +/- 1%, don't set the direction because the translation may be random jitter in the user's finger
            direction = progress > 0 ? 1 : -1
            progress = abs(progress)
        }
        progress = min(max(progress, 0), 1)
        let velocity = abs(recognizer.velocity(in: recognizer.view!.superview!).y)

        switch recognizer.state {
        case .began:
            inProgress = true
            viewController.dismiss(animated: true)
        case .changed:
            shouldCompleteTransition = progress > 0.5 || velocity > 1000
            viewController.isInteractivelyAnimatingDismissal = progress > 0.1
            update(progress)
        case .cancelled:
            inProgress = false
            cancel()
        case .ended:
            inProgress = false
            direction = nil
            if shouldCompleteTransition {
                finish()
            } else {
                cancel()
            }
        default:
            break
        }
    }
    
    override func cancel() {
        super.cancel()
        viewController?.isInteractivelyAnimatingDismissal = false
    }
    
}
