import QuartzCore
import Foundation

private func tapeChain(_ ops: [CGAffineTransform]) -> CGAffineTransform {
    ops.reversed().reduce(CGAffineTransform.identity) { $0.concatenating($1) }
}

private func tapeMove(_ x: Double, _ y: Double) -> CGAffineTransform {
    CGAffineTransform(translationX: x, y: y)
}

private func tapeScale(_ x: Double, _ y: Double) -> CGAffineTransform {
    CGAffineTransform(scaleX: x, y: y)
}

private func tapeSpin(_ degrees: Double, _ x: Double, _ y: Double) -> CGAffineTransform {
    tapeChain([tapeMove(x, y), CGAffineTransform(rotationAngle: degrees * .pi / 180), tapeMove(-x, -y)])
}

private struct TapeFrame {
    let slabFill: CGPath
    let slabStroke: CGPath
    let bodyFill: CGPath
    let bodyStroke: CGPath
    let window: CGPath
    let windowStroke: CGPath
    let line: CGPath
    let smudge: CGPath
    let rings: CGPath
    let wedges: CGPath
    let spokesSlow: CGPath
    let spokesFast: CGPath
    let puffs: CGPath
}

private enum TapeModel {
    typealias Keys = [(Double, Double)]

    static let duration = 5.2
    static let count = 156
    static let lx = 36.0
    static let rx = 84.0
    static let ry = 54.0
    static let hub = 11.0
    static let w0 = 0.6
    static let w1 = 3.6
    static let tl = 3.9
    static let th = 4.42
    static let slab = 6.5
    static let gain = 34000.0

    static let thetaKeys: Keys = [(0, 0), (3.92, 0), (4.36, Double.pi * 1.07), (4.52, Double.pi * 0.97), (4.64, Double.pi)]
    static let squashKeys: Keys = [(0, 1), (0.3, 1), (0.5, 1.06), (0.62, 0.96), (0.74, 1.02), (0.86, 1), (3.6, 1), (3.66, 0.97), (3.74, 1), (3.76, 1), (3.88, 1.14), (3.9, 1.14), (th, 1), (th + 0.04, 1.2), (th + 0.14, 0.9), (th + 0.24, 1.06), (th + 0.34, 0.97), (th + 0.44, 1.01), (th + 0.52, 1)]
    static let tiltKeys: Keys = [(0, 0), (0.3, 0), (0.5, -5), (0.64, 2), (0.76, -0.8), (0.88, 0), (3.6, 0), (3.9, 0), (4.1, -9), (4.36, 4), (th, 0), (th + 0.1, -2), (th + 0.2, 0.8), (th + 0.3, 0)]
    static let wobKeys: Keys = [(0, 0), (4.6, 0), (4.66, 3.5), (4.8, -1.5), (4.9, 0)]
    static let massKeys: Keys = [(0, 0), (w0, 0), (w1, 1)]
    static let puffSpecs: [(Double, Double, Double)] = [(24, -3, 5.2), (13, -10, 4), (34, -12, 3.2), (6, -16, 2.6)]

    static let edge: (Double, Double) = raw(1)
    static let corrL = (edge.0 / 120).rounded() * 120 - edge.0
    static let corrR = (edge.1 / 120).rounded() * 120 - edge.1

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

    static func keys(_ t: Double, _ ks: Keys) -> 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 mass(_ t: Double) -> Double { keys(t, massKeys) }

    static func radii(_ m: Double) -> (Double, Double) {
        let e = 14.5 * 14.5 - hub * hub
        let w = 20.5 * 20.5 - 14.5 * 14.5
        return (sqrt(hub * hub + e + (1 - m) * w), sqrt(hub * hub + e + m * w))
    }

    static func raw(_ m: Double) -> (Double, Double) {
        var al = 0.0
        var ar = 0.0
        let n = 80
        for j in 0..<n {
            let (rl, rr) = radii(m * (Double(j) + 0.5) / Double(n))
            al -= gain * (m / Double(n)) / rl
            ar -= gain * (m / Double(n)) / rr
        }
        return (al, ar)
    }

    static func spin(_ m: Double) -> (Double, Double) {
        let (al, ar) = raw(m)
        return (al + corrL * m, ar + corrR * m)
    }

    static func hop(_ t: Double) -> Double {
        if tl < t && t < th {
            let u = (t - tl) / (th - tl)
            return -4 * 30 * u * (1 - u)
        }
        return 0
    }

    static func point(_ cx: Double, _ cy: Double, _ r: Double, _ deg: Double) -> CGPoint {
        let b = deg * .pi / 180
        return CGPoint(x: cx + r * cos(b), y: cy + r * sin(b))
    }

    static func arc(_ path: CGMutablePath, _ cx: Double, _ cy: Double, _ r: Double, _ a0: Double, _ a1: Double) {
        path.move(to: point(cx, cy, r, a0))
        path.addArc(center: CGPoint(x: cx, y: cy), radius: r, startAngle: a0 * .pi / 180, endAngle: a1 * .pi / 180, clockwise: a1 < a0)
    }

    static func tangent(_ cx: Double, _ cy: Double, _ r: Double, _ gx: Double, _ gy: Double, _ side: Double) -> CGPoint {
        let dx = gx - cx
        let dy = gy - cy
        let d = hypot(dx, dy)
        let b = atan2(dy, dx) + acos(min(1, r / d)) * side
        return CGPoint(x: cx + r * cos(b), y: cy + r * sin(b))
    }

    static func tuck(_ cx: Double, _ cy: Double, _ p: CGPoint, _ r: Double) -> CGPoint {
        let f = (r - 3) / r
        return CGPoint(x: cx + (p.x - cx) * f, y: cy + (p.y - cy) * f)
    }

    static func ringPath(_ cx: Double, _ r: Double, into path: CGMutablePath) {
        path.addEllipse(in: CGRect(x: cx - r, y: ry - r, width: r * 2, height: r * 2))
        path.addEllipse(in: CGRect(x: cx - hub, y: ry - hub, width: hub * 2, height: hub * 2))
    }

    static func spokes(_ cx: Double, _ a: Double, _ da: Double, slow: CGMutablePath, fast: CGMutablePath, wedges: CGMutablePath) {
        let sweep = max(-100, min(100, da * 1.6))
        let sm = clamp((abs(da) - 8) / 25)
        for j in 0..<3 {
            let b = a + 120 * Double(j) + 90
            if sm > 0.02 {
                wedges.move(to: CGPoint(x: cx, y: ry))
                wedges.addLine(to: point(cx, ry, 7.5, b))
                wedges.addArc(center: CGPoint(x: cx, y: ry), radius: 7.5, startAngle: b * .pi / 180, endAngle: (b - sweep) * .pi / 180, clockwise: sweep > 0)
                wedges.closeSubpath()
            }
            let target = sm > 0.5 ? fast : slow
            target.move(to: CGPoint(x: cx, y: ry))
            target.addLine(to: point(cx, ry, 7, b))
        }
    }

    static func frame(_ index: Int) -> TapeFrame {
        let dt = duration / Double(count)
        let t = Double(index) * dt
        let m = mass(t)
        let (rl, rr) = radii(m)
        let (al, ar) = spin(m)
        let (pl, pr) = spin(mass(t - dt))
        let dl = al - pl
        let dr = ar - pr
        let sp = clamp(abs(dr) / 40)
        let theta = keys(t, thetaKeys)
        let fx = cos(theta)
        let sn = sin(theta)
        let vy = (hop(t + 0.01) - hop(t - 0.01)) / 0.02
        let air = (tl < t && t < th) ? 1 + min(0.12, abs(vy) / 1400) : 1
        let sxs = keys(t, squashKeys) / air
        let lift = hop(t)
        let tilt = keys(t, tiltKeys)
        let buzz = 0.45 * sin(t * 2 * .pi * 19) * sp
        let wob = 2.2 * sin(t * 2 * .pi * 6) * sp + keys(t, wobKeys)

        let group = tapeChain([tapeMove(buzz, lift), tapeSpin(tilt, 60, 94), tapeMove(60, 94), tapeScale(sxs, 1 / sxs), tapeMove(-60, -94)])
        let off = fx >= 0 ? slab * sn : -slab * sn
        let fxc = abs(fx) > 0.02 ? fx : 0.02
        let faceOnly = tapeChain([tapeMove(-off, 0), tapeMove(60, 0), tapeScale(fxc, 1), tapeMove(-60, 0)])
        let face = faceOnly.concatenating(group)

        func put(_ path: CGPath, _ transform: CGAffineTransform) -> CGPath {
            var t = transform
            return path.copy(using: &t) ?? path
        }

        let body = CGPath(roundedRect: CGRect(x: 10, y: 26, width: 100, height: 68), cornerWidth: 20, cornerHeight: 20, transform: nil)
        let bodyPlaced = put(body, face)
        let bodyStroke = bodyPlaced.copy(strokingWithWidth: 4, lineCap: .butt, lineJoin: .round, miterLimit: 10)
        let faceSolid = bodyPlaced.union(bodyStroke)

        let windowPath = CGMutablePath()
        windowPath.move(to: CGPoint(x: 38, y: 94))
        windowPath.addLine(to: CGPoint(x: 43, y: 84))
        windowPath.addQuadCurve(to: CGPoint(x: 46, y: 82), control: CGPoint(x: 44, y: 82))
        windowPath.addLine(to: CGPoint(x: 74, y: 82))
        windowPath.addQuadCurve(to: CGPoint(x: 77, y: 84), control: CGPoint(x: 76, y: 82))
        windowPath.addLine(to: CGPoint(x: 82, y: 94))

        let g1 = CGPoint(x: 34, y: 82)
        let g2 = CGPoint(x: 86, y: 82)
        let p1 = tuck(lx, ry, tangent(lx, ry, rl, g1.x, g1.y, 1), rl)
        let p2 = tuck(rx, ry, tangent(rx, ry, rr, g2.x, g2.y, -1), rr)
        let line = CGMutablePath()
        line.move(to: p1)
        line.addLine(to: g1)
        line.addQuadCurve(to: g2, control: CGPoint(x: 60, y: g1.y + wob))
        line.addLine(to: p2)

        let smudge = CGMutablePath()
        if sp >= 0.05 {
            let arcs = CGMutablePath()
            for (cx, r, side) in [(lx, rl, -1.0), (rx, rr, 1.0)] {
                for (a0, a1) in [(200.0, 250.0), (20.0, 70.0)] {
                    arc(arcs, cx, ry, r + 4.5, a0 + side * 10, a1 + side * 10)
                }
            }
            smudge.addPath(put(arcs.copy(strokingWithWidth: 5 * min(1, sp * 1.4), lineCap: .round, lineJoin: .round, miterLimit: 10), face))
        }

        let rings = CGMutablePath()
        ringPath(lx, rl, into: rings)
        ringPath(rx, rr, into: rings)

        let slow = CGMutablePath()
        let fast = CGMutablePath()
        let wedges = CGMutablePath()
        spokes(lx, al, dl, slow: slow, fast: fast, wedges: wedges)
        spokes(rx, ar, dr, slow: slow, fast: fast, wedges: wedges)

        var slabFill: CGPath = CGMutablePath()
        var slabStroke: CGPath = CGMutablePath()
        if abs(sn) > 0.02 {
            let ax = abs(fx)
            let hw = 50 * ax
            let xa = 60 - hw - slab * abs(sn)
            let xb = 60 + hw + slab * abs(sn)
            let corner = max(0.5, 20 * ax + slab * abs(sn) * 0.6)
            let outline = put(CGPath(roundedRect: CGRect(x: xa, y: 26, width: xb - xa, height: 68), cornerWidth: corner, cornerHeight: 20, transform: nil), group)
            slabFill = outline.subtracting(faceSolid)
            slabStroke = outline.copy(strokingWithWidth: 4, lineCap: .butt, lineJoin: .round, miterLimit: 10).subtracting(faceSolid)
        }

        let puffs = CGMutablePath()
        for side in [-1.0, 1.0] {
            for (j, spec) in puffSpecs.enumerated() {
                let u = (t - th - 0.02 * Double(j)) / 0.45
                if u > 0 && u < 1 {
                    let e = eout(u)
                    let r = spec.2 * back(u / 0.3) * (1 - ease((u - 0.4) / 0.6))
                    if r > 0.15 {
                        let x = 60 + side * (40 + spec.0 * e)
                        let y = 96 + spec.1 * e
                        puffs.addEllipse(in: CGRect(x: x - r, y: y - r, width: r * 2, height: r * 2))
                    }
                }
            }
        }

        return TapeFrame(
            slabFill: slabFill,
            slabStroke: slabStroke,
            bodyFill: bodyPlaced,
            bodyStroke: bodyStroke,
            window: put(windowPath, face),
            windowStroke: put(windowPath.copy(strokingWithWidth: 3.5, lineCap: .round, lineJoin: .round, miterLimit: 10), face),
            line: put(line.copy(strokingWithWidth: 3, lineCap: .round, lineJoin: .round, miterLimit: 10), face),
            smudge: smudge,
            rings: put(rings, face),
            wedges: put(wedges, face),
            spokesSlow: put(slow.copy(strokingWithWidth: 3.5, lineCap: .round, lineJoin: .round, miterLimit: 10), face),
            spokesFast: put(fast.copy(strokingWithWidth: 3.5, lineCap: .round, lineJoin: .round, miterLimit: 10), face),
            puffs: puffs
        )
    }
}

extension FlairLayer {
    func buildTape() {
        let unit = side
        let k = unit / 110
        let steps = TapeModel.count
        let duration = TapeModel.duration
        let frames = (0..<steps).map { TapeModel.frame($0) }
        let map = tapeChain([tapeMove(0, unit), tapeScale(k, -k), tapeMove(-5, -5), tapeMove(60, 64), tapeScale(0.84, 0.84), tapeMove(-60, -60)])
        let base = CATransform3DMakeAffineTransform(map)
        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 layer(_ path: CGPath, opacity: Float = 1, evenOdd: Bool = false) -> CAShapeLayer {
            let part = shape(path, size: full, at: .zero, in: clipper)
            part.anchorPoint = .zero
            part.position = .zero
            part.transform = base
            part.opacity = opacity
            if evenOdd { part.fillRule = .evenOdd }
            return part
        }

        let slabFill = layer(frames[0].slabFill, opacity: 0.37)
        let slabStroke = layer(frames[0].slabStroke)
        let bodyFill = layer(frames[0].bodyFill, opacity: 0.22)
        let bodyStroke = layer(frames[0].bodyStroke)
        let window = layer(frames[0].window, opacity: 0.3)
        let windowStroke = layer(frames[0].windowStroke)
        let line = layer(frames[0].line)
        let smudge = layer(frames[0].smudge, opacity: 0.35)
        let rings = layer(frames[0].rings, evenOdd: true)
        let wedges = layer(frames[0].wedges, opacity: 0.3)
        let spokesSlow = layer(frames[0].spokesSlow)
        let spokesFast = layer(frames[0].spokesFast, opacity: 0.65)
        let puffs = layer(frames[0].puffs)

        guard animating else { return }

        func paths(_ pick: (TapeFrame) -> CGPath) -> CAKeyframeAnimation {
            let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
            let animation = keyframes("path", frames.map { pick($0) }, times: times, timing: .linear)
            animation.calculationMode = .discrete
            return animation
        }

        run(group([paths { $0.slabFill }], duration: duration), on: slabFill)
        run(group([paths { $0.slabStroke }], duration: duration), on: slabStroke)
        run(group([paths { $0.bodyFill }], duration: duration), on: bodyFill)
        run(group([paths { $0.bodyStroke }], duration: duration), on: bodyStroke)
        run(group([paths { $0.window }], duration: duration), on: window)
        run(group([paths { $0.windowStroke }], duration: duration), on: windowStroke)
        run(group([paths { $0.line }], duration: duration), on: line)
        run(group([paths { $0.smudge }], duration: duration), on: smudge)
        run(group([paths { $0.rings }], duration: duration), on: rings)
        run(group([paths { $0.wedges }], duration: duration), on: wedges)
        run(group([paths { $0.spokesSlow }], duration: duration), on: spokesSlow)
        run(group([paths { $0.spokesFast }], duration: duration), on: spokesFast)
        run(group([paths { $0.puffs }], duration: duration), on: puffs)
    }
}
