package com.imin;

import android.os.Bundle;
import android.os.Handler;
import android.view.ViewGroup;
import android.widget.Toast;
import android.app.Activity;

import android.content.Context;
import android.util.Log;
import com.imin.zbar.Result;
import com.imin.zbar.ZBarScannerView;
import com.imin.IminPrinter;
import android.os.Message;
import android.os.Bundle;

public class Scan  extends Activity implements ZBarScannerView.ResultHandler {
    private ZBarScannerView mScannerView;
    private  Context context = null;
    private static final String TAG = "imin";
      public static final int SCAN_RESPONSE = 1;


    @Override
    public void onCreate(Bundle state) {
        super.onCreate(state);
        context = this;
        // setContentView(R.layout.activity_simple_scanner);
        String package_name = getApplication().getPackageName();
        setContentView(getApplication().getResources().getIdentifier("activity_simple_scanner", "layout", getApplication().getPackageName()));
        // setupToolbar();
        // ViewGroup contentFrame = (ViewGroup) findViewById(R.id.content_frame);
        ViewGroup contentFrame = (ViewGroup) findViewById(getApplication().getResources().getIdentifier("content_frame", "id", package_name));

        mScannerView = new ZBarScannerView(this.context);
        contentFrame.addView(mScannerView);
    }

    @Override
    public void onResume() {
         super.onResume();
        mScannerView.setResultHandler(this);

        mScannerView.startCamera();
    }

    @Override
    public void onPause() {
        super.onPause();
        mScannerView.stopCamera();
    }

    @Override
    public void handleResult(Result rawResult) {
    Log.d(TAG,rawResult.getContents());
    // Toast.makeText(this, "Contents = " + rawResult.getContents() +
    //           ", Format = " + rawResult.getBarcodeFormat().getName(), Toast.LENGTH_SHORT).show();
        String[] barcodes = new String[10];
        Message scanMsg = new Message();
        scanMsg.what = SCAN_RESPONSE;
        Bundle scanBundle = new Bundle();
        barcodes[0] = rawResult.getContents();
        scanBundle.putStringArray("barcodes", barcodes);
        scanMsg.setData(scanBundle);
        IminPrinter.getScanEventHandler().sendMessage(scanMsg);
        finish();
        // Note:
        // * Wait 2 seconds to resume the preview.
        // * On older devices continuously stopping and resuming camera preview can result in freezing the app.
        // * I don't know why this is the case but I don't have the time to figure out.


        // Handler handler = new Handler();
        // handler.postDelayed(new Runnable() {
        //     @Override
        //     public void run() {
        //         mScannerView.resumeCameraPreview(Scan.this);
        //     }
        // }, 2000);
    }
}
