import QuartzCore
import Foundation

private enum BikeModel {
    static let duration = 1.8
    static let count = 54
    static let rear = CGPoint(x: 38, y: 76)
    static let front = CGPoint(x: 84, y: 76)
    static let axle = 76.0
    static let ground = 94.0
    static let scale = 0.88
    static let centerX = 61.0
    static let squashKeys: [(Double, Double)] = [(0, 0), (0.2, -0.13), (0.27, 0.15), (0.42, 0), (0.74, 0.05), (0.8, -0.09), (0.89, 0.04), (0.98, -0.02), (1.1, 0)]
    static let tiltKeys: [(Double, Double)] = [(0, 0), (0.2, 3), (0.34, -7), (0.52, -6), (0.72, -3), (0.8, -2.5), (0.87, 1.5), (0.96, -0.6), (1.08, 0)]

    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let c = clamp(u); return c * c * (3 - 2 * c) }
    static func eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }

    static func keys(_ t: Double, _ ks: [(Double, Double)]) -> Double {
        if t <= ks[0].0 { return ks[0].1 }
        for (a, b) in zip(ks, ks.dropFirst()) where t <= b.0 {
            return a.1 + (b.1 - a.1) * ease((t - a.0) / (b.0 - a.0))
        }
        return ks[ks.count - 1].1
    }

    static func height(_ t: Double) -> Double {
        if t >= 0.2 && t <= 0.8 {
            let p = (t - 0.2) / 0.6
            return -4 * 15 * p * (1 - p)
        }
        if t > 0.8 && t < 1 {
            let p = (t - 0.8) / 0.2
            return -4 * 1.8 * p * (1 - p)
        }
        return 0
    }

    static func spin(_ t: Double) -> Double {
        360 * 2 * t / duration + 180 * ease((t - 0.2) / 0.6)
    }

    static func life(_ t: Double, _ t0: Double, _ dur: Double, _ rmax: Double) -> Double {
        let u = (t - t0) / dur
        if u <= 0 || u >= 1 { return 0 }
        return rmax * pow(sin(Double.pi * pow(u, 0.6)), 1.2)
    }

    static func blob(_ path: CGMutablePath, _ x: Double, _ y: Double, _ r: Double) {
        guard r > 0.05 else { return }
        path.addEllipse(in: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2))
    }

    static func effects(_ t: Double) -> (blobs: CGPath, lines: CGPath) {
        let blobs = CGMutablePath()
        let lines = CGMutablePath()
        for (dx, dy, r, d0) in [(-6.0, -3.0, 4.6, 0.0), (-13.0, -7.0, 3.6, 0.05), (-19.0, -2.0, 2.8, 0.1)] {
            let t0 = 0.2 + d0
            let u = clamp((t - t0) / 0.42)
            blob(blobs, rear.x + 2 + dx * eout(u), ground - 2 + dy * eout(u), life(t, t0, 0.42, r))
        }
        for side in [-1.0, 1.0] {
            let t0 = 0.8
            let u = clamp((t - t0) / 0.34)
            let cx = centerX + side * 20.5
            blob(blobs, cx + side * (9 + 10 * eout(u)), ground - 3 - 5 * eout(u), life(t, t0, 0.36, 4.2))
            blob(blobs, cx + side * (5 + 5 * eout(u)), ground - 9 - 6 * eout(u), life(t, t0 + 0.03, 0.3, 2.6))
        }
        let h = height(t)
        let trims = [0.0, 2.0, 3.0]
        for (j, spec) in [(79.0, 13.0, 0.0), (70.0, 9.0, 0.06), (88.0, 8.0, 0.1)].enumerated() {
            let t0 = 0.32 + spec.2
            let u = (t - t0) / 0.4
            guard u > 0 && u < 1 else { continue }
            let head = 23 - trims[j] - 3 * eout(u)
            let tail = head - spec.1 * pow(sin(Double.pi * u), 0.8)
            if head - tail > 0.3 {
                lines.move(to: CGPoint(x: tail, y: spec.0 + h + 1.5))
                lines.addLine(to: CGPoint(x: head, y: spec.0 + h + 1.5))
            }
        }
        return (blobs, lines)
    }

    static func transform(_ t: Double) -> CGAffineTransform {
        let kick = keys(t, squashKeys)
        let sy = 1 + kick
        let sx = kick > 0 ? 1 / sqrt(sy) : 1 - 0.8 * kick
        let rot = keys(t, tiltKeys) * Double.pi / 180
        var m = CGAffineTransform(translationX: -centerX, y: -ground)
        m = m.concatenating(CGAffineTransform(scaleX: sx, y: sy))
        m = m.concatenating(CGAffineTransform(translationX: centerX, y: ground))
        m = m.concatenating(CGAffineTransform(translationX: -centerX, y: -axle))
        m = m.concatenating(CGAffineTransform(rotationAngle: rot))
        m = m.concatenating(CGAffineTransform(translationX: centerX, y: axle))
        return m.concatenating(CGAffineTransform(translationX: 0, y: height(t)))
    }
}

extension FlairLayer {
    func buildBike() {
        let unit = side
        let k = unit / 110
        let duration = BikeModel.duration
        let steps = BikeModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -2 * k, ty: unit + 7 * k)
        let unmap = map.inverted()
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        func spot(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: (x - 2) * k, y: unit - (y - 7) * k) }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func scaledAbout(_ p: CGPoint) -> CGPoint {
            CGPoint(x: BikeModel.centerX + BikeModel.scale * (p.x - BikeModel.centerX), y: BikeModel.ground + BikeModel.scale * (p.y - BikeModel.ground))
        }
        func disc(_ center: CGPoint, _ r: Double) -> CGPath {
            let c = scaledAbout(center)
            let rr = r * BikeModel.scale
            return CGPath(ellipseIn: CGRect(x: c.x - rr, y: c.y - rr, width: rr * 2, height: rr * 2), transform: nil)
        }
        func holder(in parent: CALayer) -> CALayer {
            let layer = container()
            layer.removeFromSuperlayer()
            parent.addSublayer(layer)
            layer.bounds = CGRect(origin: .zero, size: full)
            return layer
        }

        let fxBlobs = shape(placed(BikeModel.effects(0).blobs), size: full, at: mid)
        fxBlobs.fillRule = .nonZero
        let fxLines = shape(placed(BikeModel.effects(0).lines), size: full, at: mid, stroke: 4 * k)
        fxLines.lineCap = .round

        let anchor = spot(BikeModel.centerX, BikeModel.ground)
        let body = holder(in: self)
        body.anchorPoint = CGPoint(x: anchor.x / unit, y: anchor.y / unit)
        body.position = anchor

        let rims = CGMutablePath()
        rims.addPath(disc(BikeModel.rear, 17))
        rims.addPath(disc(BikeModel.front, 17))
        shape(placed(rims), size: full, at: mid, in: body).opacity = 0.22
        let rimLine = shape(placed(rims), size: full, at: mid, stroke: 4 * BikeModel.scale * k, in: body)
        rimLine.lineJoin = .round

        let tubes = CGMutablePath()
        func line(_ points: [(Double, Double)]) {
            tubes.move(to: scaledAbout(CGPoint(x: points[0].0, y: points[0].1)))
            for p in points.dropFirst() { tubes.addLine(to: scaledAbout(CGPoint(x: p.0, y: p.1))) }
        }
        line([(38, 76), (58, 76), (78, 54), (84, 76)])
        line([(58, 76), (50, 54)])
        line([(42, 52), (56, 52)])
        line([(72, 46), (84, 46)])
        line([(78, 54), (78, 46)])
        let frameLine = shape(placed(tubes), size: full, at: mid, stroke: 4 * BikeModel.scale * k, in: body)
        frameLine.lineCap = .round
        frameLine.lineJoin = .round

        var wheels: [CALayer] = []
        for center in [BikeModel.rear, BikeModel.front] {
            let wheel = holder(in: body)
            let c = scaledAbout(center)
            let hub = spot(c.x, c.y)
            wheel.anchorPoint = CGPoint(x: hub.x / unit, y: hub.y / unit)
            wheel.position = hub
            let dots = CGMutablePath()
            for sign in [-1.0, 1.0] {
                let r = 2.4 * BikeModel.scale
                let x = c.x + sign * 9.5 * BikeModel.scale
                dots.addEllipse(in: CGRect(x: x - r, y: c.y - r, width: r * 2, height: r * 2))
            }
            let r = 4 * BikeModel.scale
            dots.addEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2))
            shape(placed(dots), size: full, at: mid, in: wheel)
            wheels.append(wheel)
        }

        func place(_ a: CGAffineTransform) -> (CGPoint, NSValue) {
            let layerA = unmap.concatenating(a).concatenating(map)
            let linear = CGAffineTransform(a: layerA.a, b: layerA.b, c: layerA.c, d: layerA.d, tx: 0, ty: 0)
            return (anchor.applying(layerA), NSValue(caTransform3D: CATransform3DMakeAffineTransform(linear)))
        }

        guard animating else { return }
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        func discrete(_ values: [Any]) -> CAKeyframeAnimation {
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }
        let stepTimes = (0...steps).map { Double($0) * duration / Double(steps) }
        let fx = (0..<steps).map { BikeModel.effects(Double($0) * duration / Double(steps)) }
        run(group([discrete(fx.map { placed($0.blobs) })], duration: duration), on: fxBlobs)
        run(group([discrete(fx.map { placed($0.lines) })], duration: duration), on: fxLines)
        let moves = keyframes("position", stepTimes.map { flairPoint(place(BikeModel.transform($0)).0) }, timing: .linear)
        let tilts = keyframes("transform", stepTimes.map { place(BikeModel.transform($0)).1 }, timing: .linear)
        run(group([moves, tilts], duration: duration), on: body)
        let turns = keyframes("transform.rotation.z", stepTimes.map { -BikeModel.spin($0) * Double.pi / 180 }, timing: .linear)
        for wheel in wheels {
            run(group([turns], duration: duration), on: wheel)
        }
    }
}
