//
//  UIScrollView+Extension.swift
//  Gami
//
//  Created by OneeChan on 2026/1/25.
//

import Foundation
import UIKit

private var scrollViewOriginContentInsetKey: UInt8 = 0

extension UIScrollView: LNKeyboardNotify {
    private var originContentInset: UIEdgeInsets {
        get {
            objc_getAssociatedObject(self, &scrollViewOriginContentInsetKey) as? UIEdgeInsets ?? .zero
        }
        set {
            objc_setAssociatedObject(self, &scrollViewOriginContentInsetKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
    
    func adjustKeyoard() {
        LNEventDeliver.addObserver(self)
    }
    
    func onKeyboardWillShow(curInput: UIView?, keyboardHeight: CGFloat) {
        guard let curInput, curInput.isDescendant(of: self) else { return }
        
        originContentInset = contentInset
        
        let offset = 20 + keyboardHeight
        
        let editViewY = curInput.convert(curInput.bounds, to: nil).maxY
        let distance = UIScreen.main.bounds.height - editViewY
        if distance > offset {
            return
        }
        
        var remain = offset - distance
        let curOffset = contentOffset
        let availableOffset = contentSize.height + contentInset.bottom - curOffset.y - bounds.height
        if availableOffset > remain {
            setContentOffset(.init(x: curOffset.x, y: curOffset.y + remain), animated: true)
            return
        }
        remain = remain - availableOffset
        
        
        var curInset = contentInset
        curInset.bottom += remain
        contentInset = curInset
        
        setContentOffset(.init(x: curOffset.x, y: curOffset.y + availableOffset + remain), animated: true)
    }
    
    func onKeyboardWillHide(curInput: UIView?) {
        guard let curInput, curInput.isDescendant(of: self) else { return }
        
        contentInset = originContentInset
    }
}
