import QuartzCore
import Foundation

private typealias BadumPose = [Double]

private struct BadumFrame {
    let drumBody: CGPath
    let drumTop: CGPath
    let drumSparks: CGPath
    let cymbalDisc: CGPath
    let cymbalCap: CGPath
    let cymbalSparks: CGPath
    let trailLeft: CGPath
    let stickLeft: CGPath
    let tipLeft: CGPath
    let trailRight: CGPath
    let stickRight: CGPath
    let tipRight: CGPath
}

private enum BadumModel {
    static let duration = 2.2
    static let count = 66

    static let drum = (x: 41.0, y: 56.0, z: 0.0, r: 29.0)
    static let cymbal = (x: 72.0, y: 98.0, z: 20.0, r: 15.0)
    static let lh: BadumPose = [22, -20, 32]
    static let rh: BadumPose = [78, -20, 32]
    static let hl = 0.38
    static let hr1 = 0.64
    static let hc = 1.02

    static let lrest = pose([35, 60, 3], lh)
    static let lup = pose([37, 47, 40], [lh[0], lh[1] - 2, lh[2] + 6])
    static let lhit = pose([35, 60, 0], lh)
    static let lbounce = pose([35, 56, 24], lh)
    static let rrest = pose([51, 56, 3], rh)
    static let rup = pose([51, 45, 42], [rh[0], rh[1] - 2, rh[2] + 6])
    static let rhit = pose([51, 56, 0], rh)
    static let rbounce = pose([57, 54, 28], rh)
    static let cover = pose([68, 86, 44], [74, -6, 34])
    static let chit = pose([69, 96, 21], [74, -4, 32])
    static let cbounce = pose([66, 91, 32], [74, -6, 33])

    static let ll = dist(lh, [35, 60, 0])
    static let rl = dist(rh, [51, 56, 0])

    typealias Key = (Double, BadumPose, ((Double) -> Double)?)

    nonisolated(unsafe) static let kl: [Key] = [(0, lrest, nil), (0.08, lrest, ease), (0.30, lup, eout), (hl, lhit, ein), (0.50, lbounce, eout), (0.80, lrest, back), (duration, lrest, ease)]
    nonisolated(unsafe) static let kr: [Key] = [
        (0, rrest, nil), (0.40, rrest, ease), (0.56, rup, eout), (hr1, rhit, ein), (0.74, rbounce, eout),
        (0.94, cover, ease), (hc, chit, ein), (1.16, cbounce, eout), (1.30, cbounce, ease), (1.80, rrest, back), (duration, rrest, ease),
    ]

    nonisolated(unsafe) static let frames: [BadumFrame] = (0...count).map { build(Double($0) * duration / Double(count)) }

    static func pose(_ a: BadumPose, _ b: BadumPose) -> BadumPose { a + b }
    static func dist(_ a: BadumPose, _ b: BadumPose) -> Double { sqrt(zip(a, b).reduce(0) { $0 + ($1.0 - $1.1) * ($1.0 - $1.1) }) }
    static func clamp(_ u: Double) -> Double { max(0, min(1, u)) }
    static func ease(_ u: Double) -> Double { let v = clamp(u); return v * v * (3 - 2 * v) }
    static func eout(_ u: Double) -> Double { 1 - pow(1 - clamp(u), 3) }
    static func ein(_ u: Double) -> Double { pow(clamp(u), 2.6) }
    static func back(_ u: Double) -> Double {
        let v = clamp(u) - 1
        let s = 1.6
        return 1 + (s + 1) * v * v * v + s * v * v
    }
    static func wrap(_ t: Double) -> Double {
        let m = t.truncatingRemainder(dividingBy: duration)
        return m < 0 ? m + duration : m
    }

    static func proj(_ x: Double, _ y: Double, _ z: Double) -> (Double, Double, Double) {
        let s = 1 / (1 - z / 170)
        let y0 = 122 - 0.85 * y
        return (58 + (x - 50) * 1.1 * s, 52 + (y0 - 52) * s + 0.22 * z, 1 + 0.4 * (s - 1))
    }

    static func key(_ ks: [Key], _ time: Double) -> BadumPose {
        let t = wrap(time)
        for i in 1..<ks.count {
            let (t0, p0, _) = ks[i - 1]
            let (t1, p1, f) = ks[i]
            if t <= t1 {
                let u = t1 > t0 ? (f?((t - t0) / (t1 - t0)) ?? 1) : 1
                return (0..<6).map { p0[$0] + (p1[$0] - p0[$0]) * u }
            }
        }
        return ks[ks.count - 1].1
    }

    static func tipWorld(_ p: BadumPose, _ length: Double) -> ([Double], [Double]) {
        let d = [p[0] - p[3], p[1] - p[4], p[2] - p[5]]
        let l = sqrt(d.reduce(0) { $0 + $1 * $1 })
        let n = d.map { $0 / l }
        return (Array(p[0..<3]), (0..<3).map { p[$0] - length * n[$0] })
    }

    static func decay(_ t: Double, _ h: Double, _ f: Double, _ k: Double, _ span: Double) -> Double {
        let b = wrap(t - h)
        if b > span { return 0 }
        return exp(-k * b) * cos(2 * .pi * f * b)
    }

    static func pt(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x, y: y) }

    static func ellipse(_ cx: Double, _ cy: Double, _ rx: Double, _ ry: Double) -> CGPath {
        CGPath(ellipseIn: CGRect(x: cx - rx, y: cy - ry, width: 2 * rx, height: 2 * ry), transform: nil)
    }

    static func spark(_ path: CGMutablePath, _ x: Double, _ y: Double, _ r: Double) {
        if r > 1.0 { path.addEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r)) }
    }

    static func drumShapes(_ t: Double) -> (CGPath, CGPath, CGPath) {
        func punch(_ h: Double) -> Double {
            let b = wrap(t - h)
            return b < 0.5 ? exp(-20 * b) * clamp(b / 0.03 + 0.2) : 0
        }
        let s = 0.09 * punch(hl) + 0.11 * punch(hr1) + 0.03 * punch(hc)
        let (cx, cy, sc) = proj(drum.x, drum.y, drum.z)
        let rx = drum.r * 1.1 * sc * (1 + 0.35 * s)
        let ry = drum.r * 0.68 * sc * (1 + 0.2 * s)
        let dep = 17 * (1 - 1.4 * s)
        let k = 0.5522847498
        let body = CGMutablePath()
        body.move(to: pt(cx - rx, cy))
        body.addCurve(to: pt(cx, cy + ry), control1: pt(cx - rx, cy + ry * k), control2: pt(cx - rx * k, cy + ry))
        body.addCurve(to: pt(cx + rx, cy), control1: pt(cx + rx * k, cy + ry), control2: pt(cx + rx, cy + ry * k))
        body.addLine(to: pt(cx + rx, cy + dep))
        body.addCurve(to: pt(cx, cy + dep + ry), control1: pt(cx + rx, cy + dep + ry * k), control2: pt(cx + rx * k, cy + dep + ry))
        body.addCurve(to: pt(cx - rx, cy + dep), control1: pt(cx - rx * k, cy + dep + ry), control2: pt(cx - rx, cy + dep + ry * k))
        body.closeSubpath()
        let sparks = CGMutablePath()
        for (h0, tp) in [(hl, lhit), (hr1, rhit)] {
            let b = wrap(t - h0)
            if b < 0.38 {
                let u = b / 0.38
                let (px, py, _) = proj(tp[0], tp[1], tp[2])
                for (k, a) in [-150.0, -90, -30, 90].enumerated() {
                    let r0 = (a + 20 * Double(k % 2)) * .pi / 180
                    let d = 5 + 13 * eout(u)
                    let rad = 3.0 * (1 - ease((u - 0.25) / 0.75)) * clamp(u / 0.06)
                    spark(sparks, px + d * cos(r0), py + d * 0.8 * sin(r0), rad)
                }
            }
        }
        return (body, ellipse(cx, cy, rx, ry), sparks)
    }

    static func cymbalShapes(_ t: Double) -> (CGPath, CGPath, CGPath) {
        var w = decay(t, hc, 2.3, 3.4, 1.15)
        let b = wrap(t - hc)
        if b < 1.15 { w *= clamp(b / 0.03 + 0.3) } else { w = 0 }
        let (cx, cy, sc) = proj(cymbal.x, cymbal.y, cymbal.z)
        let rx = cymbal.r * 1.1 * sc * (1 + 0.05 * abs(w))
        let ry = cymbal.r * sc * max(0.3, 0.8 - 0.45 * w)
        let a = -14 * w * .pi / 180
        let oy = cy + 4 * w
        let spin = CGAffineTransform(translationX: -cx, y: -oy).concatenating(CGAffineTransform(rotationAngle: a)).concatenating(CGAffineTransform(translationX: cx, y: oy))
        var m = spin
        let disc = ellipse(cx, oy, rx, ry).copy(using: &m) ?? ellipse(cx, oy, rx, ry)
        let capShape = ellipse(cx, oy - 1.5 * w, 4.6 * sc, 4.6 * sc * max(0.4, 0.8 - 0.45 * w))
        let cap = capShape.copy(using: &m) ?? capShape
        let sparks = CGMutablePath()
        if b < 0.55 {
            let u = b / 0.55
            for (k, ang) in [-160.0, -100, -40, 20].enumerated() {
                _ = k
                let r0 = (ang + 12 * u) * .pi / 180
                let d = 20 + 9 * eout(u)
                let rad = 3.2 * (1 - ease((u - 0.3) / 0.7)) * clamp(u / 0.08)
                spark(sparks, cx + d * cos(r0), cy + d * 0.75 * sin(r0), rad)
            }
        }
        return (disc, cap, sparks)
    }

    static func capsule(_ a: (Double, Double), _ ra: Double, _ b: (Double, Double), _ rb: Double) -> CGPath {
        let path = CGMutablePath()
        let dx = b.0 - a.0
        let dy = b.1 - a.1
        let d = hypot(dx, dy)
        if d < abs(ra - rb) + 0.1 { return path }
        let ang = atan2(dy, dx)
        let off = acos((ra - rb) / d)
        path.move(to: pt(a.0 + ra * cos(ang + off), a.1 + ra * sin(ang + off)))
        path.addLine(to: pt(b.0 + rb * cos(ang + off), b.1 + rb * sin(ang + off)))
        path.addArc(center: pt(b.0, b.1), radius: rb, startAngle: ang + off, endAngle: ang - off, clockwise: true)
        path.addLine(to: pt(a.0 + ra * cos(ang - off), a.1 + ra * sin(ang - off)))
        path.addArc(center: pt(a.0, a.1), radius: ra, startAngle: ang - off, endAngle: ang + off, clockwise: true)
        path.closeSubpath()
        return path
    }

    static func stick(_ ks: [Key], _ length: Double, _ t: Double) -> (CGPath, CGPath, CGPath) {
        let p = key(ks, t)
        let (tw, hw) = tipWorld(p, length)
        let tp = proj(tw[0], tw[1], tw[2])
        let hp = proj(hw[0], hw[1], hw[2])
        let trail = (0..<7).map { j -> (Double, Double, Double) in
            let w = tipWorld(key(ks, t - 0.012 * Double(j)), length).0
            return proj(w[0], w[1], w[2])
        }
        var run = 0.0
        for j in 0..<6 { run += hypot(trail[j + 1].0 - trail[j].0, trail[j + 1].1 - trail[j].1) }
        var trailPath: CGPath = CGMutablePath()
        if run > 20 {
            let line = CGMutablePath()
            line.addLines(between: trail.map { pt($0.0, $0.1) })
            trailPath = line.copy(strokingWithWidth: 5 * tp.2, lineCap: .round, lineJoin: .round, miterLimit: 10)
        }
        let tip = ellipse(tp.0, tp.1, 3.5 * tp.2, 3.5 * tp.2)
        return (trailPath, capsule((hp.0, hp.1), 3.6 * hp.2, (tp.0, tp.1), 2.2 * tp.2), tip)
    }

    static func build(_ t: Double) -> BadumFrame {
        let (drumBody, drumTop, drumSparks) = drumShapes(t)
        let (disc, cap, cymbalSparks) = cymbalShapes(t)
        let left = stick(kl, ll, t)
        let right = stick(kr, rl, t)
        return BadumFrame(drumBody: drumBody, drumTop: drumTop, drumSparks: drumSparks, cymbalDisc: disc, cymbalCap: cap, cymbalSparks: cymbalSparks, trailLeft: left.0, stickLeft: left.1, tipLeft: left.2, trailRight: right.0, stickRight: right.1, tipRight: right.2)
    }
}

extension FlairLayer {
    func buildBadum() {
        let unit = side
        let k = unit / 110
        let frames = BadumModel.frames
        let duration = BadumModel.duration
        let steps = BadumModel.count
        var map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: -5 * k, ty: unit + 16 * k)
        func placed(_ path: CGPath) -> CGPath { path.copy(using: &map) ?? path }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        let clipper = container()
        let tile = CAShapeLayer()
        tile.bounds = CGRect(origin: .zero, size: full)
        tile.position = mid
        tile.path = CGPath(roundedRect: CGRect(origin: .zero, size: full), cornerWidth: 22 * k, cornerHeight: 22 * k, transform: nil)
        tile.fillColor = CGColor(gray: 0, alpha: 1)
        clipper.mask = tile

        func fill(_ pick: @escaping (BadumFrame) -> CGPath, opacity: Float = 1) -> (CAShapeLayer, (BadumFrame) -> CGPath) {
            let layer = shape(placed(pick(frames[0])), size: full, at: mid, in: clipper)
            layer.opacity = opacity
            return (layer, pick)
        }
        func line(_ pick: @escaping (BadumFrame) -> CGPath, width: Double) -> (CAShapeLayer, (BadumFrame) -> CGPath) {
            let layer = shape(placed(pick(frames[0])), size: full, at: mid, stroke: width * k, in: clipper)
            layer.lineJoin = .round
            layer.lineCap = .round
            return (layer, pick)
        }
        let layers = [
            fill({ $0.drumBody }, opacity: 0.34),
            line({ $0.drumBody }, width: 4),
            line({ $0.drumTop }, width: 3.8),
            fill({ $0.drumTop }, opacity: 0.14),
            fill({ $0.drumSparks }),
            fill({ $0.cymbalDisc }, opacity: 0.22),
            line({ $0.cymbalDisc }, width: 3.6),
            fill({ $0.cymbalCap }),
            fill({ $0.cymbalSparks }),
            fill({ $0.trailLeft }, opacity: 0.3),
            fill({ $0.stickLeft }),
            fill({ $0.tipLeft }),
            fill({ $0.trailRight }, opacity: 0.3),
            fill({ $0.stickRight }),
            fill({ $0.tipRight }),
        ]

        guard animating else { return }
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        for (layer, pick) in layers {
            let values = (0..<steps).map { placed(pick(frames[$0])) }
            let animation = keyframes("path", values, times: times, timing: .linear)
            animation.calculationMode = .discrete
            run(group([animation], duration: duration), on: layer)
        }
    }
}
