//
//  PDPreviewImageControllerViewController.swift
//  PrinterDemo
//
//  Created by ios on 2019/9/11.
//  Copyright © 2019 XiamenHY. All rights reserved.
//

import UIKit

public extension CGRect {
    
    func contentRect(ratio: CGFloat, margin: CGFloat = 0) -> CGRect {
        
        let tempFrame = self.insetBy(dx: margin, dy: margin)
        if tempFrame.width/tempFrame.height > ratio {
            
            let contentWidth = ratio*tempFrame.height
            let result = tempFrame.insetBy(dx: (tempFrame.width - contentWidth)/2, dy: 0)
            return result
        }else {
            
            let contentHeight = tempFrame.width/ratio
            let result = tempFrame.insetBy(dx: 0, dy: (tempFrame.height - contentHeight)/2)
            return result
        }
    }
    
    func insetBy(edgeInset: UIEdgeInsets) -> CGRect {
        
        return CGRect.init(
            x: self.origin.x + edgeInset.left,
            y: self.origin.y + edgeInset.top,
            width: self.size.width - edgeInset.left - edgeInset.right,
            height: self.size.height - edgeInset.top - edgeInset.bottom
        )
    }
}

class PDPreviewImageControllerViewController: PDBaseViewController {

    lazy var previewImageView: UIImageView = {
        let temp = UIImageView.init()
        temp.image = self.selectedImage
        temp.backgroundColor = UIColor.white
        return temp
    }()
    
    var selectedImage : UIImage?
    var imageMode = PTBitmapMode.dithering
    
    lazy var bottomView: UIView = {
        let temp = UIView.init()
        temp.backgroundColor = UIColor.white
        temp.translatesAutoresizingMaskIntoConstraints = false
        return temp
    }()
    
    lazy var segmentImageMode : UISegmentedControl = {
        let temp = UISegmentedControl(items: ["Binary".localized,"Dithering".localized])
        temp.selectedSegmentIndex = 1
        temp.tintColor = UIColor.theme
        temp.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.black], for: UIControl.State.normal)
        temp.setTitleTextAttributes([NSAttributedString.Key.font:UIFont.systemFont(ofSize: 14),NSAttributedString.Key.foregroundColor:UIColor.white], for: UIControl.State.selected)
        temp.addTarget(self, action: #selector(selectedImageMode), for: UIControl.Event.valueChanged)
        return temp
    }()
    
    lazy var copiesLabel:UILabel = {
        let temp = UILabel.init()
        temp.text = "\(printCopiesCount)"
        temp.textAlignment = .center
        temp.textColor = UIColor.titleColor
        temp.backgroundColor = UIColor.lightDividing
        temp.font = UIFont.systemFont(ofSize: 13)
        temp.adjustsFontSizeToFitWidth = true
        return temp
    }()
    
    lazy var lessCopiesView: UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.white
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(lessPrintCopies))
        temp.isUserInteractionEnabled = true
        temp.addGestureRecognizer(tap)
        return temp
    }()
    
    lazy var addCopiesView: UIView = {
        let temp = UIView()
        temp.backgroundColor = UIColor.white
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(addPrintCopies(_:)))
        temp.isUserInteractionEnabled = true
        temp.addGestureRecognizer(tap)
        return temp
    }()
    
    lazy var printBtn : UIButton = {
        let temp = UIButton.init(type: UIButton.ButtonType.custom)
        temp.backgroundColor = UIColor.theme
        temp.setTitle("Print".localized, for: UIControl.State.normal)
        temp.setTitleColor(UIColor.white, for: UIControl.State.normal)
        temp.layer.cornerRadius = PDWidth_pt(x: 18)
        temp.translatesAutoresizingMaskIntoConstraints = false
        temp.addTarget(self, action: #selector(self.startPrint), for: UIControl.Event.touchUpInside)
        return temp
    }()
    
    var printCopiesCount = 1
    
    init(with previewImage:UIImage) {
        self.selectedImage = previewImage
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        navigationItem.title = "Print preview".localized
        view.backgroundColor = UIColor.darkDividing
    }
    
    override func configUI() {
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.bottom.equalTo(self.view.usnp.bottom)
            $0.height.equalTo(PDWidth_pt(x: 150))
        }
        
        //设置imageView的frame
        let willRect = CGRect(x: 20, y: 20 , width: kScreenWidth - 40, height: kScreenHeight - PDWidth_pt(x: 150) - kSafeAreaBottomHeight - 40 - kNavgationHeight)
        let newRect = willRect.contentRect(ratio: selectedImage!.size.width / selectedImage!.size.height)
        previewImageView.frame = newRect
        view.addSubview(previewImageView)
        
        configBottomView()
    }
    
    func configBottomView() {
        bottomView.addSubview(segmentImageMode)
        segmentImageMode.snp.makeConstraints {
            $0.left.equalToSuperview().offset(10)
            $0.right.equalToSuperview().offset(-10)
            $0.top.equalToSuperview().offset(PDWidth_pt(x: 20))
            $0.height.equalTo(PDWidth_pt(x: 40))
        }
        
        let printCopiesLb = UILabel()
        printCopiesLb.text = "Copies".localized
        printCopiesLb.textAlignment = .left
        printCopiesLb.textColor = UIColor.titleColor
        printCopiesLb.font = UIFont.systemFont(ofSize: 13)
        printCopiesLb.backgroundColor = UIColor.white
        printCopiesLb.adjustsFontSizeToFitWidth = true
        bottomView.addSubview(printCopiesLb)
        printCopiesLb.snp.makeConstraints {
            $0.left.equalTo(10)
            $0.top.equalTo(segmentImageMode.snp.bottom).offset(PDWidth_pt(x: 20))
            $0.width.equalTo(50)
            $0.height.equalTo(PDWidth_pt(x: 50))
        }
        
        bottomView.addSubview(lessCopiesView)
        lessCopiesView.snp.makeConstraints {
            $0.left.equalTo(printCopiesLb.snp.right).offset(0)
            $0.top.equalTo(printCopiesLb)
            $0.width.equalTo(50)
            $0.height.equalTo(PDWidth_pt(x: 50))
        }
        
        bottomView.addSubview(copiesLabel)
        copiesLabel.snp.makeConstraints {
            $0.left.equalTo(lessCopiesView.snp.right).offset(0)
            $0.top.equalTo(printCopiesLb)
            $0.width.equalTo(50)
            $0.height.equalTo(PDWidth_pt(x: 50))
        }
        
        bottomView.addSubview(addCopiesView)
        addCopiesView.snp.makeConstraints {
            $0.left.equalTo(copiesLabel.snp.right).offset(0)
            $0.top.equalTo(printCopiesLb)
            $0.width.equalTo(50)
            $0.height.equalTo(PDWidth_pt(x: 50))
        }
        
        let lessImage = UIImageView.init()
        lessImage.image = UIImage(named: "jian")
        lessCopiesView.addSubview(lessImage)
        lessImage.snp.makeConstraints {
            $0.center.equalToSuperview()
            $0.width.height.equalTo(PDWidth_pt(x: 16))
        }
        
        let addImage = UIImageView.init()
        addImage.image = UIImage(named: "jia")
        addCopiesView.addSubview(addImage)
        addImage.snp.makeConstraints {
            $0.center.equalToSuperview()
            $0.width.height.equalTo(PDWidth_pt(x: 16))
        }
        
        bottomView.addSubview(printBtn)
        printBtn.snp.makeConstraints {
            $0.right.equalToSuperview().offset(-10)
            $0.centerY.equalTo(copiesLabel.snp.centerY)
            $0.width.equalTo(kScreenWidth - 200 - 40)
            $0.height.equalTo(PDWidth_pt(x: 40))
        }
        
    }

}

extension PDPreviewImageControllerViewController {
    
    @objc private func lessPrintCopies() {
        
        if printCopiesCount <= 1 {
            return
        }
        printCopiesCount -= 1
        copiesLabel.text = "\(printCopiesCount)"
    }
    
    @objc private func addPrintCopies(_ sender:UITapGestureRecognizer) {
        
        if printCopiesCount >= 100 {
            return
        }
        printCopiesCount += 1
        copiesLabel.text = "\(printCopiesCount)"
    }
    
    @objc private func selectedImageMode() {
        
        if segmentImageMode.selectedSegmentIndex == 0 {
            imageMode = PTBitmapMode.binary
        }else if segmentImageMode.selectedSegmentIndex == 1 {
            imageMode = PTBitmapMode.dithering
        }
    }
    
    @objc private func startPrint() {
        
        guard let temp = selectedImage else { return }
        guard let zybImage = PDResetImage.scaleImageForWidth(image: temp, width: 832) else { return }
        
        var cmdData = Data()
        
        for _ in 0..<printCopiesCount {
            let cmd = PTCommandCPCL.init()
            cmd.cpclLabel(withOffset: 0, hRes: PTCPCLLabelResolution.resolution200, vRes: PTCPCLLabelResolution.resolution200, height: Int(zybImage.size.height) + 10, quantity: 1)
            cmd.cpclPrintBitmap(withXPos: 0, yPos: 0, image: zybImage.cgImage, bitmapMode: imageMode, compress: PTBitmapCompressMode.none)
            cmd.cpclPrint()
            cmdData.append(cmd.cmdData as Data)
        }
        
        PTDispatcher.share()?.send(cmdData)
        
        PTDispatcher.share()?.whenSendFailure({
            SVProgressHUD.showError(withStatus: "Data send failed".localized)
            
        })
        
        PTDispatcher.share()?.whenSendSuccess({
            SVProgressHUD.showSuccess(withStatus: "Data sent successfully".localized)
        })
        
        PTDispatcher.share()?.whenSendProgressUpdate({ (num) in
            guard let tempNum = num else { return }
            SVProgressHUD.showProgress(Float.init(truncating: tempNum))
        })
        
    }
}
