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

import UIKit
import PrinterSDK
import SVProgressHUD
import SwifterBaseKit

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
        if #available(iOS 13, *) {
            temp.selectedSegmentTintColor = UIColor.theme
        }else {
            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 segmentLZOMode : UISegmentedControl = {
        var temp = UISegmentedControl.init()
        if commandType == .ESC || commandType == .CPCL {
            temp = UISegmentedControl.init(items: ["Not compressed".localized,"Compression(No subcontract)".localized,"Compression(Subcontract)".localized])
            temp.selectedSegmentIndex = 2
            self.isCompress = (.none, true)
        }else {
            temp = UISegmentedControl.init(items: ["Not compressed".localized,"Compression".localized])
            temp.selectedSegmentIndex = 1
            self.isCompress = (.none, false)
        }
        
        if #available(iOS 13, *) {
            temp.selectedSegmentTintColor = UIColor.theme
        }else {
            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(selectImageCompressMode), 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.setTitleColor(UIColor.black, for: UIControl.State.highlighted)
        temp.layer.cornerRadius = 18
        temp.translatesAutoresizingMaskIntoConstraints = false
        temp.addTarget(self, action: #selector(self.startPrint), for: UIControl.Event.touchUpInside)
        return temp
    }()
    
    var printCopiesCount = 1
    
    var commandType = PTCommandType.CPCL
    var bottomViewHeight : CGFloat = 200.0
    
    fileprivate var isCompress = (PTBitmapCompressMode.none, false)
    
    init(with previewImage: UIImage, command:PTCommandType) {
        self.selectedImage = previewImage
        self.commandType = command
        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 viewWillDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        PTDispatcher.share()?.sendProgressBlock = nil
    }
    
    override func configUI() {
        
        view.addSubview(bottomView)
        bottomView.snp.makeConstraints {
            $0.left.right.equalToSuperview()
            $0.bottom.equalTo(self.view.usnp.bottom)
            $0.height.equalTo(Fitsize.fit(bottomViewHeight))
        }
        
        //设置imageView的frame
        let willRect = CGRect(x: 20, y: 20 , width: kScreenWidth - 40, height: kScreenHeight - Fitsize.fit( bottomViewHeight) - kSafeAreaBottomHeight - 40 - kSafeAreaTopHeight)
        let newRect = willRect.contentRect(ratio: selectedImage!.size.width / selectedImage!.size.height)
        previewImageView.frame = newRect
        view.addSubview(previewImageView)
        
        configBottomView()
    }
    
    func configBottomView() {
        
        bottomView.addSubview(segmentLZOMode)
        segmentLZOMode.snp.makeConstraints {
            $0.left.equalToSuperview().offset(10)
            $0.right.equalToSuperview().offset(-10)
            $0.top.equalToSuperview().offset(Fitsize.fit(15))
            $0.height.equalTo(Fitsize.fit(40))
        }
        
        bottomView.addSubview(segmentImageMode)
        segmentImageMode.snp.makeConstraints {
            $0.left.equalToSuperview().offset(10)
            $0.right.equalToSuperview().offset(-10)
            $0.top.equalTo(segmentLZOMode.snp.bottom).offset(Fitsize.fit( 15))
            $0.height.equalTo(Fitsize.fit(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(Fitsize.fit(20))
            $0.width.equalTo(50)
            $0.height.equalTo(Fitsize.fit(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(Fitsize.fit(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(Fitsize.fit( 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(Fitsize.fit(50))
        }
        
        let lessImage = UIImageView.init()
        lessImage.image = UIImage(named: "jian")
        lessCopiesView.addSubview(lessImage)
        lessImage.snp.makeConstraints {
            $0.center.equalToSuperview()
            $0.width.height.equalTo(Fitsize.fit(16))
        }
        
        let addImage = UIImageView.init()
        addImage.image = UIImage(named: "jia")
        addCopiesView.addSubview(addImage)
        addImage.snp.makeConstraints {
            $0.center.equalToSuperview()
            $0.width.height.equalTo(Fitsize.fit(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(Fitsize.fit(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 selectImageCompressMode() {
        if segmentLZOMode.selectedSegmentIndex == 0 {
            isCompress = (.none, false)
        }else if segmentLZOMode.selectedSegmentIndex == 1 {
            
            isCompress = (.LZO, false)
        }else if segmentLZOMode.selectedSegmentIndex == 2 {
            
            isCompress = (.LZO, true)
        }
    }
    
    @objc private func startPrint() {
        
        guard let temp = selectedImage else { return }
        guard let zybImage = PDResetImage.scaleImageForWidth(image: temp, width: CGFloat(kUserDefaults.integer(forKey: PDPrintDots))) else { return }
        PrintTask.beginPrint(with: zybImage, commandType, printCopiesCount, imageMode, isCompress)
    }
}
