package com.icod.yk_printer_test;


import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

import com.icod.yk_printer_test.utils.InputMethodManagerUtils;
import com.szsicod.print.escpos.PrinterAPI;
import com.szsicod.print.log.Logger;

import java.util.HashMap;
import java.util.Map;

public class SpeedActivity extends AppCompatActivity implements View.OnClickListener {
    private RadioGroup rgImageType;
    private RadioButton rgLine;
    private RadioButton rgTestG;
    private RadioButton rgTestH;
    private Button btnTestProduct;
    private Button btnPrint;
    private Button btnPrintLoop;
    private EditText etLoopNum;
    private EditText etDelayTime;
    private RadioGroup mRbtype;
    private boolean is58;

    private void findViews() {
        rgImageType = (RadioGroup)findViewById( R.id.rg_image_type );
        rgLine = (RadioButton)findViewById( R.id.rg_line );
        rgTestG = (RadioButton)findViewById( R.id.rg_test_g );
        rgTestH = (RadioButton)findViewById( R.id.rg_test_h );
        btnTestProduct = (Button)findViewById( R.id.btn_test_product );
        btnPrint = (Button)findViewById( R.id.btn_print );
        btnPrintLoop = (Button)findViewById( R.id.btn_print_loop );
        etLoopNum = (EditText)findViewById( R.id.et_loop_num );
        etDelayTime = (EditText)findViewById( R.id.et_delay_time );
        mRbtype = (RadioGroup) findViewById(R.id.rg_type);
        mRbtype.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
               is58=checkedId == R.id.cb_print_58;
                Logger.i("纸宽58", is58);

            }
        });
        mRbtype.check(R.id.cb_print_58);
        rgLine.setOnClickListener( this );
        rgTestG.setOnClickListener( this );
        rgTestH.setOnClickListener( this );
        btnTestProduct.setOnClickListener( this );
        btnPrint.setOnClickListener( this );
        btnPrintLoop.setOnClickListener( this );
        findViewById(R.id.ll_root).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Logger.i("掩藏");
                if (etDelayTime.isFocused()){
                    InputMethodManagerUtils.HideKeyBoardForView(etDelayTime);
                }  if (etLoopNum.isFocused()){
                    InputMethodManagerUtils.HideKeyBoardForView(etLoopNum);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
    if ( v == btnTestProduct ) {

        android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder(this);



     /*   attributes.type=1000;
        attributes.width=200;
        attributes.height=100;
        attributes.gravity= Gravity.CENTER;

        alertDialog.getWindow().setAttributes(attributes);*/
        builder.setCancelable(false);
        builder.setTitle(R.string.product_image_data);
        ProgressBar progressBar = new ProgressBar(this);

        builder.setView(progressBar);
        final AlertDialog alertDialog = builder.create();
         alertDialog.show();
       // alertDialog.setContentView((R.layout.progress_item));
     new Thread(new Runnable() {
         @Override
         public void run() {
             if (rgImageType.getCheckedRadioButtonId()==R.id.rg_line){
                 data=makeData();
             } else if (rgImageType.getCheckedRadioButtonId()==R.id.rg_test_g){
                 data=makeDataForG();
             }else{
                 data=makeDataForH();
             }
             SystemClock.sleep(1000);
             runOnUiThread(new Runnable() {
                 @Override
                 public void run() {
                     alertDialog.dismiss();
                 }
             });
         }
     }).start();


        } else if ( v == btnPrint ) {
          if (data==null){
              Toast.makeText(this,"没有生成数据,请先生成数据",Toast.LENGTH_LONG).show();
              return;
          }
          new Thread(new Runnable() {
              @Override
              public void run() {
                  if (PrinterAPI.getInstance().isConnect()){
                      PrinterAPI.getInstance().sendOrder(data,data.length);
                  }
              }
          }).start();
        } else if ( v == btnPrintLoop ) {
        int num=1;
        int delayTime=1;
        try {

             num = Integer.parseInt(etLoopNum.getText().toString().trim());
             delayTime = Integer.parseInt(etDelayTime.getText().toString().trim());
        }catch (Exception e){
            Logger.e(e.getMessage());

        }
        final int finalNum = num;
        final int finalDelayTime = delayTime;
        new Thread(new Runnable() {
            @Override
            public void run() {
                if (PrinterAPI.getInstance().isConnect()){
                    for (int i = 0; i < finalNum; i++) {

                        PrinterAPI.getInstance().sendOrder(data,data.length);
                        SystemClock.sleep(finalDelayTime);
                    }
                }
            }
        }).start();

    }
    }
 private byte[] data;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_speed);
        findViews();
        /*etLoopNum.setFocusable(false);
        etDelayTime.setFocusable(false);*/
        rgImageType.setFocusable(true);
        rgImageType.setFocusableInTouchMode(true);

        rgImageType.check(R.id.rg_line);

    }

/*    private byte[] makeDataForH() {
        int heigth = 120;
        int width = 384;
        int dotWidth = (width +7)/ 8;
        int dotHeight = (heigth +7)/ 8;
        int total = (dotHeight ) * dotWidth * 8;
        for (int h = 0; h < dotHeight; h++) {
            byte result[] = new byte[width+5];
            result[0] = 27;
            result[1] = 42;
            result[2]=1;
            result[3] = (byte) (width%256);
            result[4] = (byte) (width/256);
            int index=5;
        for (int w = 0; w < width; w++) {
                if (w==0||w==width-1){
                    result[index++]= -1;
                }
                else{
                    if (dotHeight/2==h) {
                        result[index++] =1<<3;
                    }else{
                        result[index++]=0;
                    }
                }

            }
            PrinterAPI.getInstance().sendOrder(result, result.length);
        }
        PrinterAPI.getInstance().printAndFeedPaper(0);
        return null;
    }*/
    //不够精确
private byte[] makeDataForH() {
        int heigth = 120;
        int width = 0;
        if (is58){
            width=384;
        }else{
            width=576;
        }
        int dotWidth = (width +7)/ 8;
        int dotHeight = heigth / 8;
        int total = heigth  * dotWidth + 8;
        byte result[] = new byte[total];
        result[0] = 29;
        result[1] = 118;
        result[2] = 48;
        result[3] = 0;
        result[4] = (byte) (dotWidth % 256);
        result[5] = (byte) (dotWidth / 256);
        result[6] = (byte) (heigth % 256);
        result[7] = (byte) (heigth  / 256);
        int index=8;
        for (int h = 0; h < heigth; h++) {
            for (int w = 0; w < dotWidth; w++) {
                if (w==0){
                    result[index++]= 1;
                }else if (w==dotWidth-1){
                    result[index++]= (byte) (1<<7);
                }
                else{
                    if (heigth/2==h) {
                        result[index++] =-1;
                    }else{
                        result[index++]=0;
                    }
                }

            }
        }

        return result;
    }

    //生成工字图形
    private byte[] makeDataForG() {

        int heigth = 1548;
        int width = 0;
        if (is58){
            width=400;
        }else{
            width=600;
        }
        int dotWidth = width / 8;
        int dotHeight = heigth / 8;
        int total = (heigth ) * dotWidth + 8;
        byte result[] = new byte[total];
        result[0] = 29;
        result[1] = 118;
        result[2] = 48;
        result[3] = 0;
        result[4] = (byte) (dotWidth % 256);
        result[5] = (byte) (dotWidth / 256);
        result[6] = (byte) ((heigth )% 256);
        result[7] = (byte) ((heigth ) / 256);
       int index=8;
        for (int h = 0; h < heigth; h++) {
            for (int w = 0; w < dotWidth; w++) {
               if (h==0||h==heigth-1){
                   result[index++]=-1;

               }else{
                   if (dotWidth/2==w) {
                       result[index++] = 1 << 3;
                   }else{
                       result[index++]=0;
                   }
               }

            }
        }

        return result;
    }


       private byte[] makeData() {
        int heigth = 120;
           int width = 0;
           if (is58){
               width=400;
           }else{
               width=584;
           }
        int dotWidth = width / 8;
        int dotHeight = 120 / 8;
        int part = 10;
        int header=2;
        int lineNum = heigth / part;
        byte[][] lineData = new byte[lineNum][width / 8];
        int offset = 0;
        int ten = 0;
        boolean isAdd = false;
        boolean isComed = false;
        for (int h = 0; h < lineNum; h++) {
            ten = 0;
            for (int w = 0; w < dotWidth; w++) {
                byte pixel = 0;
                isComed = false;
                isAdd = false;
                for (int dot = 0; dot < 8; dot++) {
                    // Logger.i("ten",ten);
                    if (!isComed) {
                        if (ten % 10 == 0) {
                            int tempPosition = 7 - dot;
                            pixel = (byte) (1 << tempPosition);
                            isAdd = true;
                            isComed = true;
                            ten=0;
                        }
                    }
                    ten++;
                }
                lineData[h][w] = pixel;

            }

        }
        int length = lineData.length;
       // Logger.i("length", length);
        int total = (heigth +(lineNum*header)) * dotWidth + 8;
        byte result[] = new byte[total];
        result[0] = 29;
        result[1] = 118;
        result[2] = 48;
        result[3] = 0;
        result[4] = (byte) (dotWidth % 256);
        result[5] = (byte) (dotWidth / 256);
        result[6] = (byte) ((heigth +(lineNum*header))% 256);
        result[7] = (byte) ((heigth +(lineNum*header)) / 256);
        boolean isOffsetOk = false;
        int index = 8;
        int isOffset = -1;
        ten=0;
           isComed=false;
           for (int i=0;i<header;i++){
               for (int i1 = 0; i1 < lineNum; i1++) {
                   for (int i2 = 0; i2 < dotWidth; i2++) {
                       if (i2 == 0||i2==12||i2==25||i2==37||i2==50||i2==62||i2==75) {
                           result[index++] = lineData[i1][i2];

                       }else{
                           result[index++]=0;
                       }
                       ten++;

                   }
               }

           }
           //整个复制数据 费时间
        HashMap<String, Byte> reset = new HashMap<>();
        //加入内容
        for (int i = 0; i < part; i++) {
            //恢复
            for (Map.Entry<String, Byte> temp : reset.entrySet()
                    ) {
                String key = temp.getKey();
                String[] split = key.split(",");
                int h = Integer.parseInt(split[0]);
                int w = Integer.parseInt(split[1]);
                lineData[h][w] = temp.getValue();

            }
            reset.clear();
            for (int h = 0; h < lineNum; h++) {
                isOffset = -1;
                isOffsetOk = false;
                for (int w = 0; w < dotWidth; w++) {
                    if (index > total - 1) {
                        return result;
                    }
                    if ((w * h) == isOffset) {
                        result[index++] = (byte) (lineData[h][w]);
                        isOffset = -1;
                        isOffsetOk = true;
                        continue;
                    }
                    byte b = lineData[h][w];
                    int bitPoition = getPoition(b);
                    //摆好位置
                    if (i > 0) {
                        if (bitPoition <=i) {
                            lineData[h][w] = 0;
                            reset.put(h + "," + (w), b);
                            if ((w + 1) < dotWidth) {
                                Byte aByte = reset.get(h + "+" + (w - 1));
                                if (aByte == null) {
                                  /*  Logger.i("i",i);
                                    Logger.i("w",w);*/
                                    int col = w - 1;
                                    byte b2;
                                    if (col >= 0)
                                        b2 = lineData[h][w - 1];
                                    else {
                                        b2 = b;
                                        int poition = getPoition(b2);
                                        int offset1 = 7 - i;
                                        if (offset1<0){
                                            lineData[h][w]=0;
                                            result[index++]=0;
                                            offset1 = Math.abs(offset1)-1;

                                            byte b1 = (byte) (1 << (7 - offset1));
                                            if (b1 < 0) {
                                                b1 = (byte) -b1;
                                            }
                                            isOffsetOk = true;
                                            reset.put(h + "," + (w + 1), lineData[h][w + 1]);
                                            lineData[h][w + 1] = b1;
                                            isOffset = h * (w + 1);
                                            continue;
                                        }else{
                                            lineData[h][w]= (byte) (Math.abs(b)>>i);
                                            result[index++]=lineData[h][w];
                                            isOffsetOk = true;
                                            continue;
                                        }
                                    }
                                    aByte = b2;
                                }
                                int poition1 = getPoition(aByte);
                                int offset1 = 0;
                                int i1 = 0;
                                if (i > poition1) {
                                    i1 = i - poition1 + 8;
                                } else {
                                    i1 = poition1 - i + 8;
                                }

                                boolean add = false;
                                boolean isComeInOffset=true;
                                if (i1 > 10) {
                                    add = true;
                                    offset1 = 10 - (poition1 - i);
                                    offset1--;
                                    if (i>7){
                                        offset1 = 7-(poition1+i-10);
                                       // com.szsicod.print.log.Logger.i("nihao");
                                        isComeInOffset=false;
                                    }
                                } else {
                                    offset1 = 10 - 8 - Math.abs(poition1 - i);
                                }
                                if (isOffsetOk) {
                                    offset1 = 10 - poition1 - 8+1;
                                    if (offset1>0){
                                        add=false;
                                        offset1--;
                                    }
                                }
                                if (offset1 < 0 || add) {
                                    lineData[h][w] = (byte) (1 << Math.abs(offset1));
                                    isOffsetOk = true;
                                    byte b1 = (byte) (lineData[h][w]);

                                    if (b1 < 0) {
                                        b1 = (byte) -b1;
                                    }
                                    result[index++] = b1;
                                    continue;
                                }
                                offset1 = Math.abs(offset1);
                                byte b1 = (byte) (1 << (7 - offset1));
                                if (b1 < 0) {
                                    b1 = (byte) -b1;
                                }
                                isOffsetOk = true;
                                reset.put(h + "," + (w + 1), lineData[h][w + 1]);
                                lineData[h][w + 1] = b1;
                                isOffset = h * (w + 1);

                            }
                        }
                    }
                    byte b1 = (byte) (lineData[h][w] >> i);

                    if (b1 < 0) {
                        b1 = (byte) -b1;
                    }
                    result[index++] = b1;
                    isOffsetOk = false;

                }
            }
        }
        return result;
    }

    private int getPoition(byte b) {
        int bit = 0;
        if ((b & 1) > 0) {
            return 1;
        }
        if ((b & 2) > 0) {
            return 2;
        }
        if ((b & 4) > 0) {
            return 3;
        }
        if ((b & 8) > 0) {
            return 4;
        }
        if ((b & 16) > 0) {
            return 5;
        }
        if ((b & 32) > 0) {
            return 6;
        }
        if ((b & 64) > 0) {
            return 7;
        }
        if ((b & 128) > 0) {
            return 8;
        }
        return 0;
    }

    private int getValueWithPoition(byte b) {
        int bit = 0;

        if (b == 6) {
            return 32;
        }
        if (b == 1) {
            return 1;
        }
        if (b == 2) {
            return 2;
        }
        if (b == 3) {
            return 8;
        }
        if (b == 4) {
            return 16;
        }
        if (b == 5) {
            return 32;
        }
        if (b == 7) {
            return 64;
        }
        if (b == 8) {
            return 128;
        }
        return 0;
    }

}
