//
//  LogTableView.swift
//  MpAccDemo
//

import UIKit
import SnapKit

fileprivate class LogCell: UITableViewCell {
    
    lazy var titleLabel: UILabel = {
        let lb = UILabel()
        lb.numberOfLines = 2
        return lb
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: .default, reuseIdentifier: reuseIdentifier)
        self.contentView.addSubview(self.titleLabel)
        self.titleLabel.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

class LogTableView: UITableView {
    
    private var logArr:[String] = []
    var maxLog: Int = 100
    
    private let queue = DispatchQueue(label: "com.tencent.logqueue")
    
    init() {
        super.init(frame: .zero, style: .plain)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        super.init(frame: .zero, style: .plain)
        setupUI()
    }
    
    override init(frame: CGRect, style: UITableView.Style) {
        super.init(frame: frame, style: style)
        setupUI()
    }
    
    private func setupUI() {
        self.register(LogCell.self, forCellReuseIdentifier: "LogCell")
        self.estimatedRowHeight = 50
        self.dataSource = self
    }
    
    func appendLog(logStr: String) {
        DispatchQueue.main.async {
            if self.logArr.count > self.maxLog {
                self.logArr.remove(at: 0)
                self.deleteRows(at: [IndexPath(row: 0, section: 0)], with: .none)
            }
            self.logArr.append(logStr)
            self.insertRows(at: [IndexPath(row: self.logArr.count - 1, section: 0)], with: .none)
            self.scrollToRow(at: IndexPath(row: self.logArr.count - 1, section: 0), at: .top, animated: true)
        }
    }
}

extension LogTableView: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        logArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "LogCell", for: indexPath) as! LogCell
        cell.titleLabel.text = logArr[indexPath.row]
        return cell
    }
}
