package ai.pai.lensman.session;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Base64;
import android.util.Log;

import com.gprinter.aidl.GpService;
import com.gprinter.command.EscCommand;
import com.gprinter.command.GpCom;
import com.gprinter.service.GpPrintService;

import org.apache.commons.lang.ArrayUtils;

import java.util.ArrayList;
import java.util.Vector;

import ai.pai.lensman.App;
import ai.pai.lensman.bean.PhotoBean;
import ai.pai.lensman.bean.SessionBean;
import ai.pai.lensman.db.DBService;
import ai.pai.lensman.service.UploadService;


public class SessionPresenter implements SessionContract.Presenter, SessionInteractor.SessionListener {

    private SessionInteractor interactor;
    private ArrayList<PhotoBean> photoList;
    private SessionContract.View sessionView;
    private SessionBean sessionBean;
    private boolean isWorking;

    private GpService mGpService = null;
    private PrinterServiceConnection conn = null;
    private int mPrinterId = 0;


    public SessionPresenter(SessionBean sessionBean, SessionContract.View view) {
        this.sessionView = view;
        this.sessionBean = sessionBean;
        interactor = new SessionInteractor(sessionBean, this);
    }

    @Override
    public void start() {
        photoList = DBService.getInstance().getPhotoListBySessionId(sessionBean.sessionId);
        if (photoList.size() == 0) {
            sessionView.showEmptyView();
        } else {
            sessionView.showPhotoRecyclerView();
            for (PhotoBean photoBean : photoList) {
                sessionView.addNewPhoto(photoBean);
            }
        }
        interactor.startSession();
        startAndBindPrintService();
    }

    @Override
    public void stop() {
        interactor.endSession();
        isWorking = false;
        if (conn != null) {
            App.getAppContext().unbindService(conn);
        }
    }

    @Override
    public void onSessionStartSuccess(String session) {
        isWorking = true;
        sessionView.showToast("session启动成功");
    }

    @Override
    public void onSessionStartError(String session) {
        sessionView.showToast("session启动失败,自动重试中");
        interactor.startSession();
    }

    @Override
    public void onSessionPhotoCaptured(final PhotoBean bean) {
        if (!isWorking) {
            return;
        }
        DBService.getInstance().addPhotoBean(bean);
        sessionView.showPhotoRecyclerView();
        sessionView.addNewPhoto(bean);
        App.getAppContext().startService(new Intent(App.getAppContext(), UploadService.class));
    }

    @Override
    public void onSessionEnd(String session) {

    }

    @Override
    public void swipeToDeletePhoto(int index) {
        PhotoBean photoBean = photoList.get(index);
        photoList.remove(photoBean);
        DBService.getInstance().deletePhotoBean(photoBean);
        interactor.deletePhoto(photoBean);
    }

    @Override
    public void printQR() {
        EscCommand esc = new EscCommand();
        esc.addPrintAndFeedLines((byte) 3);
        esc.addSelectJustification(EscCommand.JUSTIFICATION.CENTER);//设置打印居中
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.ON, EscCommand.ENABLE.ON, EscCommand.ENABLE.OFF);//设置为倍高倍宽
        esc.addText("Sample\n");   //  打印文字
        esc.addPrintAndLineFeed();

		/*打印文字*/
        esc.addSelectPrintModes(EscCommand.FONT.FONTA, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF, EscCommand.ENABLE.OFF);//取消倍高倍宽
        esc.addSelectJustification(EscCommand.JUSTIFICATION.LEFT);//设置打印左对齐
        esc.addText("Welcome to use Paiai!\n");   //  打印文字

		/*QRCode命令打印
			此命令只在支持QRCode命令打印的机型才能使用。
			在不支持二维码指令打印的机型上，则需要发送二维条码图片
		*/
        esc.addText("Print QRcode\n");   //  打印文字
        esc.addSelectErrorCorrectionLevelForQRCode((byte) 0x31); //设置纠错等级
        esc.addSelectSizeOfModuleForQRCode((byte) 3);//设置qrcode模块大小
        esc.addStoreQRCodeData(sessionBean.sessionId);//设置qrcode内容
        esc.addPrintQRCode();//打印QRCode
        esc.addPrintAndLineFeed();

        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(mPrinterId, str);
            GpCom.ERROR_CODE r = GpCom.ERROR_CODE.values()[rel];
            if (r != GpCom.ERROR_CODE.SUCCESS) {
                sessionView.showToast( GpCom.getErrorText(r));
            }
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }

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

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

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

}
