package com.mayi.fastdevelop.commonpage.zxing;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.google.zxing.Result;
import com.mayi.fastdevelop.R;
import com.mayi.fastdevelop.base.BaseActivity;
import com.mayi.fastdevelop.commonpage.zxing.camera.CameraManager;
import com.mayi.fastdevelop.commonpage.zxing.decoding.CaptureActivityHandler;
import com.mayi.fastdevelop.commonpage.zxing.decoding.InactivityTimer;
import com.mayi.fastdevelop.commonpage.zxing.view.ViewfinderView;
import com.mayi.fastdevelop.view.CustomTitleBar;
import com.mayi.fastdevelop.view.OnMultiClickListener;

import java.io.IOException;

/**
 * 扫描
 * 进入页面前要进行权限判断
 */
public abstract class BaseScanActivity extends BaseActivity implements Callback {

    private static final long VIBRATE_DURATION = 100L;
    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private InactivityTimer inactivityTimer;
    private boolean vibrate;
    private boolean flag = true;
    private SurfaceView surfaceView;
    CustomTitleBar mCustomTitleBar;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_scanner);
        CameraManager.init(getApplicationContext());
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        surfaceView = findViewById(R.id.scanner_view);
        viewfinderView = findViewById(R.id.viewfinder_content);
        initTitleBar();
    }

    private void initTitleBar() {
        mCustomTitleBar = findViewById(R.id.im_view_title);
        mCustomTitleBar.setTextLeft("");
        mCustomTitleBar.setTextCenter(getString(R.string.capture));
        mCustomTitleBar.setLeftImageResource(R.mipmap.icon_back);
        mCustomTitleBar.setOnClickLeftViewListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                finish();
            }
        });
        mCustomTitleBar.setTextRight(getString(R.string.open_light));
        mCustomTitleBar.setOnClickRightTextListener(new OnMultiClickListener() {
            @Override
            public void onMultiClick(View v) {
                light();
            }
        });
    }

    /**
     * 打开闪光灯
     */
    protected void light() {
        if (flag) {
            flag = false;
            CameraManager.get().openLight();
            mCustomTitleBar.setTextRight(getString(R.string.close_light));
        } else {
            flag = true;
            CameraManager.get().offLight();
            mCustomTitleBar.setTextRight(getString(R.string.open_light));
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        vibrate = true;
    }

    @Override
    protected void onPause() {
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
        if (!hasSurface) {
            SurfaceHolder surfaceHolder = surfaceView.getHolder();
            surfaceHolder.removeCallback(this);
        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        inactivityTimer.shutdown();
    }

    /**
     * 处理程序扫描结果
     */
    public void handleDecode(Result result) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        handleData(result.getText());
    }

    public abstract void handleData(String resultString);

    /**
     * 重启扫描
     */
    public void restartPreview() {
        Message message = new Message();
        message.what = R.id.restart_preview;
        if (handler == null) handler = new CaptureActivityHandler(this);
        handler.sendMessageDelayed(message, 2000);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            e.printStackTrace();
            Toast.makeText(this, getString(R.string.error_take_photo), Toast.LENGTH_LONG).show();
            return;
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void playBeepSoundAndVibrate() {
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            if (vibrator != null) {
                vibrator.vibrate(VIBRATE_DURATION);
            }
        }
    }

}