//
//  TSBaseOperation.swift
//  AIRingtone
//
//  Created by 100Years on 2025/3/20.
//

import Foundation

class TSBaseOperation: Operation , @unchecked Sendable{
    
    let uuid:String
    
    enum TSBaseOperationState {
        case executing(Bool)
        case finished(Bool)
        case cancelled(Bool)
    }
    
    @Published var operationStatePblished:TSBaseOperationState = .executing(false)
    
    private var _executing = false
    private var _finished = false
    private var _cancelled = false
    private var _error: Error?
    
    required init(uuid:String) {
        self.uuid = uuid
        super.init()
    }
    
    // MARK: - State Management
    
    override var isExecuting: Bool {
        return _executing
    }
    
    override var isFinished: Bool {
        return _finished
    }
    
    override var isCancelled: Bool {
        return _cancelled
    }
    
    override var isAsynchronous: Bool {
        return true
    }
    
    override func start() {
        if isCancelled {
            finished()
            return
        }
        setExecutingValue(value: true)
    }
    
    override func cancel() {
        debugPrint("TSBaseOperation cancel")
        cancelCleanContent()
        setCancelValue(value: true)
        if isExecuting {
            finished()
        }
    }
    
    func finished() {
        if _executing {
            setExecutingValue(value: false)
        }
        
        if !_finished {
            setFinishedValue(value: true)
        }
    }
    
    func setCancelValue(value:Bool){
        willChangeValue(forKey: "isCancelled")
        _cancelled = value
        didChangeValue(forKey: "isCancelled")
        operationStatePblished = .cancelled(value)
    }
    
    func setExecutingValue(value:Bool){
        willChangeValue(forKey: "isExecuting")
        _executing = value
        didChangeValue(forKey: "isExecuting")
        operationStatePblished = .executing(value)
    }
    
    func setFinishedValue(value:Bool){
        willChangeValue(forKey: "isFinished")
        _finished = value
        didChangeValue(forKey: "isFinished")
        operationStatePblished = .finished(value)
    }
    
    // MARK: - Error Handling
    
    var error: Error? {
        return _error
    }
    
    // MARK: - Convenience Methods
    
    override func waitUntilFinished() {
        while !isFinished {
            RunLoop.current.run(mode: .default, before: .distantFuture)
        }
    }
    
    func addDependency(_ operation: TSBaseOperation) {
        super.addDependency(operation)
    }
    
    func removeDependency(_ operation: TSBaseOperation) {
        super.removeDependency(operation)
    }
    
    //子类重写,退出清理内容
    func cancelCleanContent() {
        fatalError("必须重写 cancelCleanContent")
    }
    
    
    deinit {
        debugPrint("♻️♻️♻️ \(type(of: self)) deinit ♻️♻️♻️")
    }
}
