//
//  DiyElementBaseView.swift
//  ClockWidget
//
//  Created by fff on 2024/7/2.
//

import UIKit
import Combine

class DiyElementBaseView: HYHAddImageView, DiyElementView {
    lazy var observers: [AnyCancellable] = []
    
    var element: DiyElement
    init(element: DiyElement) {
        self.element = element
        super.init(frame: CGRect(origin: .zero, size: .zero))
        self.isEditing = false
        
        backgroundColor = .clear
        setupContentView()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    deinit {
        observers.forEach({ $0.cancel() })
        observers.removeAll()
    }
    
    // 子类重写, 添加内容
    func setupContentView() {}
    
    /// 设置约束
    func setupLayout(with config: DiyElementTransform) {
        var space = ElementEditInset
        if supportEditActions() == .none {
            space = 0.0
        }
        
        self.snp.makeConstraints { make in
            make.center.equalTo(config.position)
            if let size = config.size {
                if size != CGSize.zero {
                    make.size.equalTo(CGSize(width: size.width+space*2, height: size.height+space*2))
                }
            } else if let maxWidth = config.maxWidth {
                make.width.lessThanOrEqualTo(maxWidth+space*2)
            } else {
                make.width.lessThanOrEqualTo(UIScreen.width-80)
            }
        }
        if let angle = config.rotateAngle {
            self.transform = CGAffineTransform(rotationAngle: angle*CGFloat.pi/180.0)
        }
    }
    
    lazy var scene = DiyElementScene.detail
    
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        var space = ElementEditInset
        if supportEditActions() == .none {
            space = 0.0
        }
        // 设置边框颜色
        context.setStrokeColor(UIColor.assist.cgColor)
        
        let showLine = element.showCornerLine && isEditing
        // 设置边框的线宽
        context.setLineWidth(showLine ? 1.0 : 0)
        context.setLineDash(phase: 2, lengths: [6, 6])
        context.setLineCap(.round)
        
        let path = UIBezierPath(roundedRect: CGRect(x: space, y: space, width: rect.width-space*2, height: rect.height-space*2), cornerRadius: 8)
        context.addPath(path.cgPath)
        
        // 画线
        context.strokePath()
    }
    
    
    
    
    override func layoutSubviews() {
        super.layoutSubviews()
   
    }
    
    override func supportEditActions() -> EditElementAction {
        return element.supportEditActions
    }
    
    func setContentView(corRadius: CGFloat) {
        contentView.cornerRadius = corRadius
        contentView.clipsToBounds = true
    }
    
    func setState(isPreview: Bool) {}
}
