import QuartzCore
import Foundation

private enum DouseItem {
    case circle(Double, Double, Double)
    case ellipse(Double, Double, Double, Double)
    case line([CGPoint], Double)
}

private struct DouseFrame {
    let water: CGPath
    let can: CGAffineTransform
}

private enum DouseModel {
    static let duration = 2.9
    static let count = 87
    static let gy = 90.0
    static let bx0 = 16.0
    static let bx1 = 56.0
    static let sp0 = (x: 50.0, y: 80.0)
    static let sp1 = (x: 74.0, y: 56.0)
    static let rl = 6.0
    static let rr = 6.5
    static let bc = (x: 36.0, y: 74.0)
    static let e0 = 1.0
    static let e1 = 1.56
    static let gravity = 900.0
    static let vs = 58.0

    static let ang: [(Double, Double)] = [(0, 0), (0.4, 0), (0.72, -14), (0.84, -14), (1.04, 40), (1.16, 30), (1.28, 34), (1.56, 33), (1.8, 0), (1.92, -4), (2.04, 1.5), (2.14, 0)]
    static let xs: [(Double, Double)] = [(0, 0), (0.84, 0), (1.04, -10), (1.6, -10), (1.8, 0)]
    static let lift: [(Double, Double)] = [(0, 0), (0.84, 0), (1.04, 21), (1.16, 16), (1.28, 19), (1.56, 19), (1.78, 0)]
    static let sq: [(Double, Double)] = [(0, 0), (0.4, 0), (0.72, 0.14), (0.84, 0.14), (0.94, -0.12), (1.06, 0.03), (1.16, 0), (1.76, 0), (1.82, 0.16), (1.94, -0.06), (2.06, 0.02), (2.14, 0)]

    static let emit: [Double] = (0...90).map { e0 + Double($0) * (e1 - e0) / 90 }
    static let landing: [Double] = emit.map { landTime($0) }
    static let landX: [Double] = zip(emit, landing).map { dropState($0, $1).0 }
    nonisolated(unsafe) static let frames: [DouseFrame] = (0...count).map { build(Double($0) * duration / Double(count)) }

    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 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 pivot(_ t: Double) -> (x: Double, y: Double) {
        keys(t, ang) < 0 ? (bx0, gy) : bc
    }

    static func apply(_ t: Double, _ p: (Double, Double)) -> (Double, Double) {
        let a = keys(t, ang)
        let q = keys(t, sq)
        let l = keys(t, lift)
        let piv = pivot(t)
        let mx = (bx0 + bx1) / 2
        let y = gy + (p.1 - gy) * (1 - q)
        let x = mx + (p.0 - mx) * (1 + 0.6 * q)
        let r = a * .pi / 180
        let dx = x - piv.x
        let dy = y - piv.y
        return (piv.x + keys(t, xs) + dx * cos(r) - dy * sin(r), piv.y - l + dx * sin(r) + dy * cos(r))
    }

    static func unit() -> (Double, Double, Double) {
        let dx = sp1.x - sp0.x
        let dy = sp1.y - sp0.y
        let l = hypot(dx, dy)
        return (dx / l, dy / l, l)
    }

    static func spoutDir(_ t: Double) -> (Double, Double) {
        let a = keys(t, ang) * .pi / 180
        let (ux, uy, _) = unit()
        return (ux * cos(a) - uy * sin(a), ux * sin(a) + uy * cos(a))
    }

    static func face(_ k: Double) -> (Double, Double) {
        let (ux, uy, l) = unit()
        return (sp0.x + ux * (l + rl) - uy * rr * k, sp0.y + uy * (l + rl) + ux * rr * k)
    }

    static func mouth(_ t: Double) -> (Double, Double) { apply(t, face(0)) }

    static func canTransform(_ t: Double) -> CGAffineTransform {
        let a = keys(t, ang)
        let q = keys(t, sq)
        let l = keys(t, lift)
        let piv = pivot(t)
        let mx = (bx0 + bx1) / 2
        var m = CGAffineTransform(translationX: -mx, y: -gy)
        m = m.concatenating(CGAffineTransform(scaleX: 1 + 0.6 * q, y: 1 - q))
        m = m.concatenating(CGAffineTransform(translationX: mx, y: gy))
        m = m.concatenating(CGAffineTransform(translationX: -piv.x, y: -piv.y))
        m = m.concatenating(CGAffineTransform(rotationAngle: a * .pi / 180))
        m = m.concatenating(CGAffineTransform(translationX: piv.x, y: piv.y))
        return m.concatenating(CGAffineTransform(translationX: keys(t, xs), y: -l))
    }

    static func dropState(_ te: Double, _ t: Double) -> (Double, Double) {
        let m = mouth(te)
        let d = spoutDir(te)
        let u = t - te
        let v = vs * (1 + 0.5 * exp(-(te - e0) / 0.12)) * clamp((te - e0 + 0.03) / 0.05)
        return (m.0 + d.0 * v * u, m.1 + d.1 * v * u + 0.5 * gravity * u * u)
    }

    static func landTime(_ te: Double) -> Double {
        var lo = te
        var hi = te + 1.5
        for _ in 0..<40 {
            let mid = (lo + hi) / 2
            if dropState(te, mid).1 < gy - 2 { lo = mid } else { hi = mid }
        }
        return lo
    }

    static func water(_ t: Double) -> [DouseItem] {
        var out: [DouseItem] = []
        func blob(_ x: Double, _ y: Double, _ r: Double) { if r > 0.1 { out.append(.circle(x, y, r)) } }
        var pts: [(Double, Double, Double)] = []
        for (i, te) in emit.enumerated() where te <= t && t < landing[i] {
            let (x, y) = dropState(te, t)
            var r = 2.6 + 0.35 * sin(2 * .pi * (te * 6.5 - t * 2)) + 1.6 * clamp(1 - (te - e0) / 0.06)
            r *= 0.3 + 0.7 * pow(clamp((e1 - te) / 0.12), 0.6)
            pts.append((x, y, r))
        }
        for (p0, p1) in zip(pts, pts.dropFirst()) {
            out.append(.line([CGPoint(x: p0.0, y: p0.1), CGPoint(x: p1.0, y: p1.1)], p0.2 + p1.2))
        }
        if let first = pts.first { blob(first.0, first.1, first.2) }
        if let last = pts.last { blob(last.0, last.1, last.2) }
        let landed = (0..<emit.count).filter { landing[$0] <= t }.map { landX[$0] }
        if !landed.isEmpty {
            let cx = min(landed.reduce(0, +) / Double(landed.count), 90)
            let w = 5 + 13 * eout(Double(landed.count) / 70)
            let sh = 1 - ease((t - 1.8) / 0.85)
            let sw = 1 + 0.09 * sin(2 * .pi * t * 4.5) * (1 - clamp((t - 1.6) / 0.6))
            if sh > 0.02 {
                out.append(.ellipse(cx - 0.2 * w * sh, gy - 1.5, w * sh * sw, 4.6 * sqrt(sh) / sw))
            }
        }
        if t < e0 {
            let m = apply(t, face(0.75))
            let r = 3.6 * (1 + 0.12 * sin(t * 9))
            blob(m.0, m.1 + r * 0.8, r)
        } else {
            let u = (t - 2.35) / 0.45
            if u > 0 {
                let m = apply(t, face(0.75))
                let r = 3.6 * eout(u)
                blob(m.0, m.1 + r * 0.8, r)
            }
        }
        for j in [0, 22] {
            let tl = landing[j]
            let x0 = landX[j]
            let big = j == 0 ? 1.0 : 0.75
            for (side, vx, vy, r) in [(-1.0, 40.0, 120.0, 3.4), (1, 36, 105, 3.0), (-1, 20, 140, 2.6), (1, 14, 135, 2.4)] {
                let u = t - tl
                if u > 0 && u < 0.42 {
                    let x = x0 + side * vx * u * (1 + 0.15 * Double(j % 3))
                    let y = gy - 3 - vy * big * u + 0.5 * 620 * u * u
                    if y < gy { blob(x, y, r * big * sqrt(1 - u / 0.42)) }
                }
            }
        }
        return out
    }

    static func build(_ t: Double) -> DouseFrame {
        DouseFrame(water: contour(water(t), 2.0), can: canTransform(t))
    }

    static func blur(_ field: inout [Float], _ w: Int, _ h: Int, _ radius: Int) {
        let inv = 1 / Float(2 * radius + 1)
        var cum = [Float](repeating: 0, count: max(w, h) + 1)
        for _ in 0..<3 {
            for y in 0..<h {
                let base = y * w
                for x in 0..<w { cum[x + 1] = cum[x] + field[base + x] }
                for x in 0..<w { field[base + x] = (cum[min(x + radius + 1, w)] - cum[max(x - radius, 0)]) * inv }
            }
            for x in 0..<w {
                for y in 0..<h { cum[y + 1] = cum[y] + field[y * w + x] }
                for y in 0..<h { field[y * w + x] = (cum[min(y + radius + 1, h)] - cum[max(y - radius, 0)]) * inv }
            }
        }
    }

    static func contour(_ items: [DouseItem], _ sigma: Double) -> CGPath {
        let path = CGMutablePath()
        guard !items.isEmpty else { return path }
        let res = 2.0
        var minX = Double.infinity
        var minY = Double.infinity
        var maxX = -Double.infinity
        var maxY = -Double.infinity
        func grow(_ x: Double, _ y: Double, _ r: Double) {
            minX = min(minX, x - r)
            maxX = max(maxX, x + r)
            minY = min(minY, y - r)
            maxY = max(maxY, y + r)
        }
        for item in items {
            switch item {
            case let .circle(x, y, r): grow(x, y, r)
            case let .ellipse(x, y, rx, ry): grow(x, y, max(rx, ry))
            case let .line(ps, w): ps.forEach { grow(Double($0.x), Double($0.y), w / 2) }
            }
        }
        let pad = sigma * 3.5 + 1
        let x0 = max(minX - pad, -14)
        let y0 = max(minY - pad, -16)
        let x1 = min(maxX + pad, 120)
        let y1 = min(maxY + pad, 110)
        guard x1 > x0, y1 > y0 else { return path }
        let w = Int(ceil((x1 - x0) * res)) + 2
        let h = Int(ceil((y1 - y0) * res)) + 2
        guard let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w, space: CGColorSpaceCreateDeviceGray(), bitmapInfo: CGImageAlphaInfo.none.rawValue) else { return path }
        ctx.translateBy(x: 0, y: CGFloat(h))
        ctx.scaleBy(x: 1, y: -1)
        ctx.scaleBy(x: res, y: res)
        ctx.translateBy(x: -x0, y: -y0)
        ctx.setFillColor(gray: 1, alpha: 1)
        ctx.setStrokeColor(gray: 1, alpha: 1)
        ctx.setLineCap(.round)
        ctx.setLineJoin(.round)
        for item in items {
            switch item {
            case let .circle(x, y, r):
                ctx.fillEllipse(in: CGRect(x: x - r, y: y - r, width: 2 * r, height: 2 * r))
            case let .ellipse(x, y, rx, ry):
                ctx.fillEllipse(in: CGRect(x: x - rx, y: y - ry, width: 2 * rx, height: 2 * ry))
            case let .line(ps, width):
                ctx.setLineWidth(width)
                ctx.addLines(between: ps)
                ctx.strokePath()
            }
        }
        guard let data = ctx.data?.assumingMemoryBound(to: UInt8.self) else { return path }
        var field = (0..<(w * h)).map { Float(data[$0]) / 255 }
        let box = max(1, Int((sqrt(4 * sigma * res * sigma * res + 1) - 1) / 2 + 0.5))
        blur(&field, w, h, box)
        for x in 0..<w {
            field[x] = 0
            field[(h - 1) * w + x] = 0
        }
        for y in 0..<h {
            field[y * w] = 0
            field[y * w + w - 1] = 0
        }
        let level: Float = 0.45
        var links: [Int: [Int]] = [:]
        func link(_ a: Int, _ b: Int) {
            links[a, default: []].append(b)
            links[b, default: []].append(a)
        }
        for r in 0..<(h - 1) {
            for c in 0..<(w - 1) {
                let tl = field[r * w + c]
                let tr = field[r * w + c + 1]
                let br = field[(r + 1) * w + c + 1]
                let bl = field[(r + 1) * w + c]
                let index = (tl > level ? 1 : 0) | (tr > level ? 2 : 0) | (br > level ? 4 : 0) | (bl > level ? 8 : 0)
                if index == 0 || index == 15 { continue }
                let cell = (r * w + c) * 2
                let top = cell
                let bottom = ((r + 1) * w + c) * 2
                let leftEdge = cell + 1
                let rightEdge = (r * w + c + 1) * 2 + 1
                let centre = (tl + tr + br + bl) / 4 > level
                switch index {
                case 1, 14: link(leftEdge, top)
                case 2, 13: link(top, rightEdge)
                case 3, 12: link(leftEdge, rightEdge)
                case 4, 11: link(rightEdge, bottom)
                case 6, 9: link(top, bottom)
                case 7, 8: link(leftEdge, bottom)
                case 5:
                    if centre { link(top, rightEdge); link(leftEdge, bottom) } else { link(leftEdge, top); link(rightEdge, bottom) }
                default:
                    if centre { link(leftEdge, top); link(rightEdge, bottom) } else { link(top, rightEdge); link(leftEdge, bottom) }
                }
            }
        }
        func point(_ id: Int) -> CGPoint {
            let cell = id / 2
            let c = cell % w
            let r = cell / w
            var px = Double(c)
            var py = Double(r)
            if id % 2 == 0 {
                let f0 = field[r * w + c]
                let f1 = field[r * w + c + 1]
                px += Double((level - f0) / (f1 - f0))
            } else {
                let f0 = field[r * w + c]
                let f1 = field[(r + 1) * w + c]
                py += Double((level - f0) / (f1 - f0))
            }
            return CGPoint(x: x0 + (px + 0.5) / res, y: y0 + (py + 0.5) / res)
        }
        var seen = Set<Int>()
        for start in links.keys.sorted() where !seen.contains(start) {
            var loop: [CGPoint] = []
            var current = start
            var previous = -1
            while true {
                loop.append(point(current))
                seen.insert(current)
                guard let next = links[current]?.first(where: { $0 != previous && !seen.contains($0) }) else { break }
                previous = current
                current = next
            }
            if loop.count > 2 {
                path.addLines(between: loop)
                path.closeSubpath()
            }
        }
        return path
    }

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

    nonisolated(unsafe) static let body: CGPath = {
        let path = CGMutablePath()
        path.move(to: p(20, 88))
        path.addLine(to: p(52, 88))
        path.addQuadCurve(to: p(56.5, 83), control: p(57, 88))
        path.addLine(to: p(54, 66))
        path.addQuadCurve(to: p(46, 59), control: p(53, 59))
        path.addLine(to: p(26, 59))
        path.addQuadCurve(to: p(18, 66), control: p(19, 59))
        path.addLine(to: p(15.5, 83))
        path.addQuadCurve(to: p(20, 88), control: p(15, 88))
        path.closeSubpath()
        return path
    }()

    nonisolated(unsafe) static let handle: CGPath = {
        let path = CGMutablePath()
        path.move(to: p(31, 62))
        path.addCurve(to: p(7, 62), control1: p(31, 36), control2: p(2, 38))
        path.addCurve(to: p(19, 76), control1: p(8.5, 69), control2: p(13, 73))
        return path
    }()

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

    static var spoutAngle: Double { atan2(sp1.y - sp0.y, sp1.x - sp0.x) }

    static var spoutFrame: CGAffineTransform {
        CGAffineTransform(rotationAngle: spoutAngle).concatenating(CGAffineTransform(translationX: sp0.x, y: sp0.y))
    }

    static var spout: CGPath {
        let ln = unit().2
        let path = CGMutablePath()
        path.move(to: p(-4, -6))
        path.addLine(to: p(ln, -3.4))
        path.addLine(to: p(ln, 3.4))
        path.addLine(to: p(-4, 6))
        path.closeSubpath()
        return placed(path, spoutFrame)
    }

    static var rose: CGPath {
        let ln = unit().2
        let path = CGMutablePath()
        path.move(to: p(ln - 1, -3))
        path.addLine(to: p(ln + rl - 0.5, -rr))
        path.addQuadCurve(to: p(ln + rl - 0.5, rr), control: p(ln + rl + 1.8, 0))
        path.addLine(to: p(ln - 1, 3))
        path.closeSubpath()
        return placed(path, spoutFrame)
    }
}

extension FlairLayer {
    func buildDouse() {
        let unit = side
        let k = unit / 110
        let frames = DouseModel.frames
        let duration = DouseModel.duration
        let steps = DouseModel.count
        let map = CGAffineTransform(a: k, b: 0, c: 0, d: -k, tx: 4 * k, ty: unit + 6 * k)
        let inverse = map.inverted()
        func placed(_ path: CGPath) -> CGPath { DouseModel.placed(path, map) }
        let full = CGSize(width: unit, height: unit)
        let mid = CGPoint(x: unit / 2, y: unit / 2)
        func holder(in parent: CALayer) -> CALayer {
            let layer = container()
            layer.removeFromSuperlayer()
            parent.addSublayer(layer)
            return layer
        }
        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

        let can = holder(in: clipper)
        can.bounds = CGRect(origin: .zero, size: full)
        can.anchorPoint = .zero
        can.position = .zero

        let behind = holder(in: can)
        behind.bounds = CGRect(origin: .zero, size: full)
        behind.position = mid
        let hole = CGMutablePath()
        hole.addRect(CGRect(x: 0, y: 0, width: 3 * unit, height: 3 * unit))
        hole.addPath(placed(DouseModel.body), transform: CGAffineTransform(translationX: unit, y: unit))
        hole.addPath(placed(DouseModel.rose), transform: CGAffineTransform(translationX: unit, y: unit))
        let cut = CAShapeLayer()
        cut.frame = CGRect(x: -unit, y: -unit, width: 3 * unit, height: 3 * unit)
        cut.path = hole
        cut.fillRule = .evenOdd
        cut.fillColor = CGColor(gray: 0, alpha: 1)
        behind.mask = cut

        let outer = DouseModel.handle.copy(strokingWithWidth: 11.5, lineCap: .round, lineJoin: .round, miterLimit: 10)
        let inner = DouseModel.handle.copy(strokingWithWidth: 4.4, lineCap: .round, lineJoin: .round, miterLimit: 10)
        let ring = CGMutablePath()
        ring.addPath(placed(outer))
        ring.addPath(placed(inner))
        shape(ring, size: full, at: mid, in: behind).fillRule = .evenOdd
        shape(placed(inner), size: full, at: mid, in: behind).opacity = 0.22
        shape(placed(DouseModel.spout), size: full, at: mid, in: behind).opacity = 0.22
        let spoutLine = shape(placed(DouseModel.spout), size: full, at: mid, stroke: 3 * k, in: behind)
        spoutLine.lineJoin = .round

        shape(placed(DouseModel.rose), size: full, at: mid, in: can).opacity = 0.22
        let roseLine = shape(placed(DouseModel.rose), size: full, at: mid, stroke: 3 * k, in: can)
        roseLine.lineJoin = .round

        shape(placed(DouseModel.body), size: full, at: mid, in: can).opacity = 0.22
        let bodyLine = shape(placed(DouseModel.body), size: full, at: mid, stroke: 4 * k, in: can)
        bodyLine.lineJoin = .round

        let water = shape(placed(frames[0].water), size: full, at: mid, in: clipper)
        water.fillRule = .evenOdd

        guard animating else { return }
        let values = (0..<steps).map { placed(frames[$0].water) }
        let times = (0..<steps).map { NSNumber(value: Double($0) / Double(steps)) }
        let paths = keyframes("path", values, times: times, timing: .linear)
        paths.calculationMode = .discrete
        run(group([paths], duration: duration), on: water)
        let moves = keyframes("transform", frames.map { NSValue(caTransform3D: CATransform3DMakeAffineTransform(inverse.concatenating($0.can).concatenating(map))) }, timing: .linear)
        run(group([moves], duration: duration), on: can)
    }
}
