//
//  ViewController.swift
//  PrinterDemo
//
//  Created by ios on 2021/12/18.
//  Copyright © 2021 Printer. All rights reserved.
//

import UIKit
import SVProgressHUD
import PrinterSDK
import Reusable
import SwifterBaseKit

class PDFPreviewViewController: PDBaseViewController {

    @IBOutlet weak var countLb: UILabel!
    @IBOutlet weak var printButton: UIButton!
    @IBOutlet weak var modeSegment: UISegmentedControl!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var compressSegment: UISegmentedControl!
    
    fileprivate var counter = 1
    fileprivate var imageMode = PTBitmapMode.dithering
    fileprivate var generator : PDFConvertible
    fileprivate var dataProviders = [PDFDataProvider]()
    fileprivate var cache = PDFImageCache()
    fileprivate var selectedIndexPath = IndexPath.init(item: 0, section: 0)
    fileprivate var isCompress = (PTBitmapCompressMode.none, false)
    fileprivate var cmdType = PTCommandType.ESC
    
    fileprivate lazy var layoutGuide: UILayoutGuide = {
        let temp = UILayoutGuide()
        view.addLayoutGuide(temp)
        return temp
    }()
    
    init(with generator: PDFConvertible, cmdType: PTCommandType) {
        self.generator = generator
        self.cmdType = cmdType
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "PDF"
        view.backgroundColor = kRGBACOLOR(r: 242, g: 242, b: 242, a: 1)
    }
    
    override func configUI() {
        countLb.text = "1"
        makeCollectionView()
        makeModeSegment()
        loadPDFDataSource()
        printButton.cornerRadius = 5
    }

    @IBAction func didSubAction(_ sender: Any) {
        if counter <= 1 {
            return
        }
        counter -= 1
        countLb.text = "\(counter)"
    }
    
    @IBAction func didAddAction(_ sender: Any) {
        counter += 1
        countLb.text = "\(counter)"
    }
    
    @IBAction func didPrintImageAction(_ sender: Any) {
        didPrintImage()
    }
    
    deinit {
        
    }
}

extension PDFPreviewViewController {
    
    private func makeModeSegment() {
        modeSegment.selectedSegmentIndex = 1
        if #available(iOS 13, *) {
            modeSegment.selectedSegmentTintColor = UIColor.theme
        }else {
            modeSegment.tintColor = UIColor.theme
        }
        modeSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.black], for: UIControl.State.normal)
        modeSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.white], for: UIControl.State.selected)
        modeSegment.addTarget(self, action: #selector(self.selectedImageMode), for: UIControl.Event.valueChanged)
        
        compressSegment.selectedSegmentIndex = 0
        if #available(iOS 13, *) {
            compressSegment.selectedSegmentTintColor = UIColor.theme
        }else {
            compressSegment.tintColor = UIColor.theme
        }
        compressSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.black], for: UIControl.State.normal)
        compressSegment.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.white], for: UIControl.State.selected)
        compressSegment.addTarget(self, action: #selector(self.selectCompressMode), for: UIControl.Event.valueChanged)
    }
    
    private func makeCollectionView() {
        let flowLayout = PDFRollViewFlowLayout()
        flowLayout.minimumLineSpacing = 30
        flowLayout.minimumInteritemSpacing = 30
        flowLayout.scrollDirection = .horizontal
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(10)
            make.bottom.equalTo(-150 - kSafeAreaBottomHeight)
        }
        
        flowLayout.itemSize = CGSize.init(width: kScreenWidth - 10, height: kScreenHeight - 160 - kSafeAreaBottomHeight - kSafeAreaTopHeight)
        collectionView.collectionViewLayout = flowLayout
        collectionView.register(cellType: PDFPreviewCell.self)
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.isPagingEnabled = false
        collectionView.decelerationRate = UIScrollView.DecelerationRate(rawValue: 0.3)
        collectionView.backgroundColor = kRGBACOLOR(r: 242, g: 242, b: 242, a: 1)
    }
    
    private func loadPDFDataSource() {
        dataProviders = generator.generate(A4.getSize()).map {
            return PDFDataProvider.init(with: $0, outputSize: A4.getSize())
        }
    }
}

extension PDFPreviewViewController {
    
    @objc private func selectedImageMode() {
        print("11")
        if modeSegment.selectedSegmentIndex == 0 {
            imageMode = PTBitmapMode.binary
        }else if modeSegment.selectedSegmentIndex == 1 {
            imageMode = PTBitmapMode.dithering
        }
    }
    
    @objc private func selectCompressMode() {
        if compressSegment.selectedSegmentIndex == 0 {
            isCompress = (.none, false)
        }else if compressSegment.selectedSegmentIndex == 1 {
            isCompress = (.LZO, false)
        }else {
            isCompress = (.LZO, true)
        }
    }
}

extension PDFPreviewViewController {
    
    private func didPrintImage() {
        if let generator = self.cache.cachedImage(at: selectedIndexPath.item) {
            guard let resultImage = generator.previewImage else {
                return
            }
            let shapeImage = PTBitmapManager.image(toSharpen: resultImage)
            PrintTask.beginPrint(with: shapeImage, cmdType, counter, imageMode, isCompress)
        }
    }
}

extension PDFPreviewViewController : UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return dataProviders.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(for: indexPath, cellType: PDFPreviewCell.self)
        let item = dataProviders[indexPath.item]

        if let generator = self.cache.cachedImage(at: indexPath.item) {
            cell.previewImage.image = generator.previewImage
        }else {
            DispatchQueue.global().async {
                item.getOriginImage()
                DispatchQueue.main.async {
                    cell.previewImage.image = item.previewImage
                }
            }
            self.cache.append(generator: item, index: indexPath.item)
        }
        cell.pageLb.text = "\(indexPath.item + 1)"
        return cell
    }
    
//    func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
//        guard let cell = cell as? PDFPreviewCell else {
//            return
//        }
//
//    }
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        guard let currentIndexPath = collectionView.indexPathForItem(at: view.convert(collectionView.center, to: collectionView)) else { return }
        selectedIndexPath = currentIndexPath
    }
}

class PDFPreviewCell: PDBaseCollectionViewCell {
    
    lazy var previewImage: UIImageView = {
        let temp = UIImageView()
        temp.contentMode = .scaleAspectFit
        contentView.addSubview(temp)
        return temp
    }()
    
    lazy var pageLb: UILabel = {
        let temp = UILabel()
        temp.textColor = .white
        temp.font = UIFont.pingFang(size: 15)
        temp.textAlignment = .center
        temp.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        contentView.addSubview(temp)
        return temp
    }()
    
    override func configUI() {
        backgroundColor = kRGBACOLOR(r: 242, g: 242, b: 242, a: 1)
        previewImage.snp.makeConstraints { $0.edges.equalToSuperview() }
        
        pageLb.snp.makeConstraints { make in
            make.left.right.bottom.equalTo(0)
            make.height.equalTo(30)
        }
    }
}


