package ai.pai.lensman.printer;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.IBinder;
import android.util.Base64;
import android.util.Log;

import com.android.common.utils.LogHelper;
import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.io.PortParameters;
import com.gprinter.service.GpPrintService;

import org.apache.commons.lang.ArrayUtils;

import java.util.Vector;

import ai.pai.lensman.R;
import ai.pai.lensman.db.Preferences;


public class PrinterService extends Service {

    private GpService mGpService;
    private GpServiceConnection conn = null;

    public static final int ERROR_CODE_PRINTER_SERVICE_OFF = 1000;
    public static final int ERROR_CODE_PRINTER_SERVICE_EXCEPTION = 2000;

    private static final String TAG = "PrinterService";


    class GpServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "onServiceDisconnected() called");
            mGpService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "onServiceConnected() called");
            mGpService = GpService.Stub.asInterface(service);
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new PrintServiceBinder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if(mGpService == null){
            startAndBindPrintService();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (conn != null) {
            unbindService(conn);
        }
    }


    private void startAndBindPrintService() {
        Intent intent = new Intent(this, GpPrintService.class);
        startService(intent);
        conn = new GpServiceConnection();
        bindService(intent, conn, Context.BIND_AUTO_CREATE);
    }

    public String queryPrinterStatus() {
        String str;
        try {
            int status = mGpService.queryPrinterStatus(0, 10000);
            if (status == GpCom.STATE_NO_ERR) {
                str = "打印机正常";
                Preferences.getInstance().setPrinterConnected(true);
            } else {
                Preferences.getInstance().setPrinterConnected(false);
                str = "打印机 ";
                if ((byte) (status & GpCom.STATE_OFFLINE) > 0) {
                    str += "脱机";
                }
                if ((byte) (status & GpCom.STATE_PAPER_ERR) > 0) {
                    str += "缺纸";
                }
                if ((byte) (status & GpCom.STATE_COVER_OPEN) > 0) {
                    str += "打印机开盖";
                }
                if ((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) {
                    str += "打印机出错";
                }
                if ((byte) (status & GpCom.STATE_TIMES_OUT) > 0) {
                    str += "查询超时";
                }
            }

        } catch (Exception e1) {
            str = getString(R.string.printer_status_query_fail);
        }
        return str;
    }

    public int printQR(String qrCodeStr) {
        if(mGpService==null){
            return ERROR_CODE_PRINTER_SERVICE_OFF;
        }
        EscCommand esc = new EscCommand();
		/*打印文字*/
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF,
                EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍宽
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印左对齐
        esc.addText("拍爱\n");   //  打印文字
        esc.addPrintAndLineFeed();
		/*QRCode命令打印
			此命令只在支持QRCode命令打印的机型才能使用。
			在不支持二维码指令打印的机型上，则需要发送二维条码图片
		*/
        esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31); //设置纠错等级
        esc.addSelectSizeOfModuleForQRCode((byte)8);//设置qrcode模块大小
        esc.addStoreQRCodeData(qrCodeStr);//设置qrcode内容
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印中心对齐
        esc.addPrintQRCode();//打印QRCode
        esc.addPrintAndFeedLines((byte) 1);

        Vector<Byte> datas = esc.getCommand(); //发送数据
        Byte[] Bytes = datas.toArray(new Byte[datas.size()]);
        byte[] bytes = ArrayUtils.toPrimitive(Bytes);
        String str = Base64.encodeToString(bytes, Base64.DEFAULT);
        int rel;
        try {
            rel = mGpService.sendEscCommand(0, str);
        } catch (Exception e) {
            rel = ERROR_CODE_PRINTER_SERVICE_EXCEPTION;
        }
        return rel;
    }

    public int connectPrinter(BluetoothDevice device) {
        if(mGpService==null){
            return ERROR_CODE_PRINTER_SERVICE_OFF;
        }
        int code ;
        try {
             code = mGpService.openPort(0, PortParameters.BLUETOOTH, device.getAddress(), 0);
            LogHelper.d(TAG,"open port return code ="+code);
        } catch (Exception e) {
            LogHelper.e(TAG,"connectPrinter open port error "+e);
            code = ERROR_CODE_PRINTER_SERVICE_EXCEPTION;
        }
        return code;
    }

    public class PrintServiceBinder extends Binder {

        public PrinterService getService(){
            return PrinterService.this;
        }

    }

}
