package chaoran.business.engine.impl;

/*
 **********************************************
 *      DATE           PERSON       REASON
 *    2021-02-19          FXY        Created
 **********************************************
 */


import android.content.Context;
import android.widget.Toast;
import chaoran.business.engine.PrintEngine;
import chaoran.business.engine.entity.Setting;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 简单串口打印机
 */
public class SimplePrintEngine implements PrintEngine {

    //ip地址
    private String address;
    //端口
    private Integer port;
    //上下文
    private Context context;

    private SimplePrintEngine() {
    }

    public SimplePrintEngine(Context context, String address, Integer port) {
        this.context = context;
        this.address = address;
        this.port = port;
    }

    @Override
    public void print(File file) {
        print(file, address, port);
    }

    //--------------------------此处如果需要持久化，参考蓝牙打印机引擎类------------------------------//
    @Override
    public Setting getSetting() {
        return null;
    }

    @Override
    public boolean saveSetting(Setting s) {
        return false;
    }
    //------------------------持久化需要，参考蓝牙打印引擎类-----------------------------------------//

    private void print(File file, String address, Integer port) {
        //打印机端口默认9100
        if (port == -1)
            port = 9100;
        Socket socket = null;
        FileInputStream fis = null;
        try {
            socket = new Socket(address, port);
            OutputStream out = socket.getOutputStream();
            fis = new FileInputStream(file);
            byte[] buf = new byte[1024];
            int len = 0;
            //判断是否读到文件末尾
            while ((len = fis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            //告诉服务端，文件已传输完毕
            socket.shutdownOutput();
            socket.close();
            fis.close();
        } catch (IOException e) {
            Toast.makeText(context, "打印文件出错！", Toast.LENGTH_SHORT).show();
            try {
                socket.shutdownOutput();
                socket.close();
                fis.close();
            } catch (IOException ioException) {
                Toast.makeText(context, "断开与打印机的连接时出错！", Toast.LENGTH_SHORT).show();
                ioException.printStackTrace();
            }
        }
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }
}
