package w.soulofpluto.camera;

import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.hardware.Camera;
import android.os.Build;
import android.os.Environment;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.FrameLayout;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;
import static w.soulofpluto.camera.Constants.deleteCache;
import static w.soulofpluto.camera.Constants.hideKeyboard;
import static w.soulofpluto.camera.Model.OrderbyID;

public class MainActivity extends AppCompatActivity implements View.OnFocusChangeListener {
    private static final int STORAGE_PERMISSION_REQUEST_CODE = 1 ;
    private DataBaseHelper dataBaseHelper;
    private HashMap<String, File> filesHashMap = new HashMap<>();
    private RecyclerView  list;
    private EditText      autotext;
    private FrameLayout   image_layout;
    private Camera        mCamera;
    private CameraPreview mPreview;
    private String        BarcodeValue;
    private ArrayList<Model> arrayList;
    private CustomAdapter customAdapter;
    int ALL_PERMISSIONS = 101;
    private boolean safeToTakePicture = false;
    private int RequestCode = 2;
    private Boolean connect = false;
    public Menu globalMenuItem;
    private String ScannerData ="";
    PreferenceManager preferenceManager;
    private int Total = 0;
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list              =  findViewById(R.id.list);
        autotext          =  findViewById(R.id.autotext);
        //RDSTJENS00021178           =  findViewById(R.id.RDSTJENS00021178);
        dataBaseHelper    = new DataBaseHelper(this);
        autotext.addTextChangedListener(new AutoChecked());
        arrayList = new ArrayList<>();
        /*RDSTJENS00021178.addTextChangedListener(new AutoChecked());*/
        //autotext.requestFocus();
        System.out.println("Database ====>"+dataBaseHelper.gettotalCount());
        if(dataBaseHelper.gettotalCount()>0)
        updateDatabaseValues();
        runtimepermission();
        hideKeyboard(MainActivity.this);
        preferenceManager = new PreferenceManager(this);
        if(getIntent().getStringExtra("key") != null){
            if(getIntent().getStringExtra("key").equalsIgnoreCase("success")){
                if(preferenceManager.getID().length() > 0){
                    if(preferenceManager.getID().equalsIgnoreCase(String.valueOf(dataBaseHelper.gettotalCount()))){
                        Total = Integer.parseInt(preferenceManager.getID());
                    }else if(Integer.parseInt(preferenceManager.getID()) > dataBaseHelper.gettotalCount()){
                        Total = Integer.parseInt(preferenceManager.getID());
                    }else{
                        Total = dataBaseHelper.gettotalCount();
                    }
                }else{
                   Total = dataBaseHelper.gettotalCount();
                }
                System.out.println("DataSize if ===>" + Total);
            }
        }else{
            Total = dataBaseHelper.gettotalCount();
            System.out.println("DataSize else ===>"+Total);
        }
         try {
             customAdapter = new CustomAdapter(this, arrayList);
             list.setLayoutManager(new LinearLayoutManager(MainActivity.this));
             list.setAdapter(customAdapter);
         }catch (NullPointerException np){
             np.printStackTrace();
         }
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        getMenuInflater().inflate(R.menu.menu, menu);
        globalMenuItem = menu;
        globalMenuItem.findItem(R.id.menu_take_picture).setVisible(false);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
     public boolean onOptionsItemSelected(@NonNull MenuItem item){
        switch (item.getItemId()){
            case R.id.menu_scan:
                if(Constants.isNetworkAvailable(MainActivity.this)) {
                    IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
                    ArrayList<String> data = new ArrayList<>();
                    data.add("CODE_128");
                    intentIntegrator.setDesiredBarcodeFormats(data);
                    intentIntegrator.setBeepEnabled(true);
                    intentIntegrator.setCameraId(0);
                    intentIntegrator.setPrompt("SCAN");
                    intentIntegrator.setBarcodeImageEnabled(false);
                    intentIntegrator.initiateScan();
                }else{
                  Constants.getToast(MainActivity.this,"Please check your internet connection");
                }

                //startScanningBarcode();
             break;
            case R.id.menu_take_picture:
                if(safeToTakePicture) {
                    safeToTakePicture = false;
                    mCamera.takePicture(null, null, mPicture);
                }
             break;
            case R.id.menu_logout:
                if(dataBaseHelper.gettotalCount()>0) {
                    Cursor c = dataBaseHelper.getData();
                    if (c != null && c.moveToFirst()) {
                            do {
                                if (c.getInt(c.getColumnIndex("status")) == 0) {
                                    final Model model = new Model();
                                    model.setID(c.getInt(c.getColumnIndex("_id")));
                                    model.setSKU(c.getString(c.getColumnIndex("sku")));
                                    model.setFILEPATH(c.getString(c.getColumnIndex("filename")));
                                    model.setSTATUS(c.getInt(c.getColumnIndex("status")));
                                    final int     finalId       = c.getInt(c.getColumnIndex("_id"));
                                    final String  finalsku      = c.getString(c.getColumnIndex("sku"));
                                    final String  finalfilename = c.getString(c.getColumnIndex("filename"));
                                    try {
                                        Handler handler = new Handler();
                                        handler.postDelayed(
                                                new Runnable() {
                                                    public void run() {
                                                        if (Constants.isNetworkAvailable(MainActivity.this)){
                                                            NetworkCall(finalId,finalsku, finalfilename, model);
                                                        } else {
                                                            Constants.getToast(MainActivity.this, "Check your internet connection");
                                                        }
                                                    }
                                                }, 500);

                                    }catch (ArrayIndexOutOfBoundsException ae){
                                        ae.printStackTrace();
                                    }

                                }//arrayList.add(model);
                            } while (c.moveToNext());
                        }
                }
               preferenceManager.setLogged(false);
               preferenceManager.setUserId("");
               preferenceManager.setPassword("");
               preferenceManager.setID(String.valueOf(dataBaseHelper.gettotalCount()));
               dataBaseHelper.deleteData();
                if(dataBaseHelper.gettotalCount()  == 0){
                    System.out.println("Check if ===>"+preferenceManager.getID());
                }else{
                    System.out.println("Check else===>"+preferenceManager.getID());
                    preferenceManager.setID(String.valueOf(dataBaseHelper.gettotalCount()));
                }
               //MyApplication.getInstance().clearApplicationData();
               deleteCache(MainActivity.this);
               try{
                   mCamera.release();
                   image_layout.removeAllViews();
                   Intent in = new Intent(this,LoginActivity.class);
                   startActivity(in);
                   finish();
               }catch(RuntimeException re){
                   re.printStackTrace();
               }
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    private Boolean name(String data){
        Pattern regex = Pattern.compile("[$~&+,:;=\\\\?@#|/'<>^*()%!-]");
        if(regex.matcher(data).find()){
           return true;
        }
        return false;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data){
        IntentResult Result = IntentIntegrator.parseActivityResult(requestCode , resultCode ,data);
        if(Result != null){
            if(Result.getContents() == null){
                Log.i("MainActivity" , "cancelled scan");
                //Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show();
            }
            else {
                Log.i("MainActivity" , "Scanned");
                //Toast.makeText(this,"Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show();
                ScannerData = Result.getContents();
                if(name(ScannerData)) {
                    if(Constants.isNetworkAvailable(MainActivity.this)) {
                   /* Intent intent=new Intent(MainActivity.this,BarcodeScannerActivity.class);
                    startActivityForResult(intent, RequestCode);*/
                        IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);
                        ArrayList<String> data1 = new ArrayList<>();
                        data1.add("CODE_128");
                        intentIntegrator.setDesiredBarcodeFormats(data1);
                        intentIntegrator.setBeepEnabled(true);
                        intentIntegrator.setCameraId(0);
                        intentIntegrator.setPrompt("SCAN");
                        intentIntegrator.setBarcodeImageEnabled(false);
                        intentIntegrator.initiateScan();
                    }else{
                        Constants.getToast(MainActivity.this,"Please check your internet connection");
                    }
                    //System.out.println("Scanner if====>" +Result.getContents());
                    //Constants.getToast(MainActivity.this,"Scanner if"+Result.getContents());
                }else{
                    System.out.println("Scanner else====>" +Result.getContents());
                    //Constants.getToast(MainActivity.this,"Scanner else"+Result.getContents());
                    globalMenuItem.findItem(R.id.menu_scan).setVisible(false);
                    globalMenuItem.findItem(R.id.menu_take_picture).setVisible(true);
                    connect = true;
                }
            }
        }
        else {
            super.onActivityResult(requestCode , resultCode , data);
        }


        /*if(resultCode != RESULT_CANCELED){
            if(requestCode == RequestCode){
                System.out.println("Scanner ====>" +data.getStringExtra("MESSAGE"));
                ScannerData = data.getStringExtra("MESSAGE");
                if(name(ScannerData)) {
                    if(Constants.isNetworkAvailable(MainActivity.this)){
                        Intent intent=new Intent(MainActivity.this,BarcodeScannerActivity.class);
                        startActivityForResult(intent, RequestCode);
                    }else{
                        Constants.getToast(MainActivity.this,"Please check your internet connection");
                    }
                    System.out.println("Scanner if====>" +data.getStringExtra("MESSAGE"));
                }else{
                    System.out.println("Scanner else====>" +data.getStringExtra("MESSAGE"));
                    globalMenuItem.findItem(R.id.menu_scan).setVisible(false);
                    globalMenuItem.findItem(R.id.menu_take_picture).setVisible(true);
                    connect = true;
                }
            }
        }*/

        super.onActivityResult(requestCode, resultCode, data);
    }

    private void runtimepermission(){
        if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED){
           final String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                   Manifest.permission.READ_EXTERNAL_STORAGE};
           ActivityCompat.requestPermissions(this, permissions, ALL_PERMISSIONS);
        }else{
           take_priview();
        }
        if(!Constants.isNetworkAvailable(this)){
           Constants.getToast(this, "check internet connection");
        }else{
           ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
           STORAGE_PERMISSION_REQUEST_CODE);
        }
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        switch(requestCode){
            case 101:
                boolean isPerpermissionForAllGranted = false;
                if(grantResults.length > 0 && permissions.length==grantResults.length){
                    for(int i = 0; i < permissions.length; i++){
                        if(grantResults[i] == PackageManager.PERMISSION_GRANTED){
                            isPerpermissionForAllGranted=true;
                            take_priview();
                        }else{
                            isPerpermissionForAllGranted=false;
                        }
                    }
                }else{
                    isPerpermissionForAllGranted=true;
                }
                if(isPerpermissionForAllGranted){
                }
                break;
            default:
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @Override
    public void onFocusChange(View view, boolean b) {
        autotext.requestFocus();
    }
    class AutoChecked implements TextWatcher{
        public void afterTextChanged(Editable s){
        }
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }
        public void onTextChanged(CharSequence s, int start, int before, int count){
            try{
                if(s.toString().length() > 4){
                    BarcodeValue = s.toString();
                    System.out.println("Barcode ===>"+BarcodeValue);
                    if (s.toString().toLowerCase().contains("capture")){
                        if(safeToTakePicture) {
                            if(Constants.isNetworkAvailable(MainActivity.this)){
                                safeToTakePicture = false;
                                connect = false;
                                mCamera.takePicture(null, null, mPicture);
                            }else{
                                Constants.getToast(MainActivity.this,"Please check your internet connection");
                            }
                        }
                    }else if (s.toString().toLowerCase().contains("@apture")){
                        autotext.setText("");
                        autotext.requestFocus();
                    }else if (s.toString().toLowerCase().contains("@lpture")){
                        autotext.setText("");
                        autotext.requestFocus();
                    }
                }
            }catch(NumberFormatException nfe){
                nfe.printStackTrace();
            }
        }
    }

    @Override
    protected void onResume() {
       if(mCamera !=null) {
          //mCamera.startPreview();
          release();
       }
       super.onResume();
    }

    private void take_priview(){
        mCamera          = getCameraInstance();
        mPreview         = new CameraPreview(this, mCamera);
        image_layout     = findViewById(R.id.image_layout);
        image_layout.addView(mPreview);
    }

    private Camera getCameraInstance(){
        Camera camera = null;
        try {
            camera = Camera.open();
            Camera.Parameters params = camera.getParameters();
            List<Camera.Size> allSizes = params.getSupportedPictureSizes();
            Camera.Size size = allSizes.get(0);
            for (int i = 0; i < allSizes.size(); i++) {
                if (allSizes.get(i).width > size.width)
                    size = allSizes.get(i);
            }
            params.setPictureSize(size.width,size.height);
            params.setJpegQuality(50);
            if(params!=null) {
                camera.setParameters(params);
            }
            camera.startPreview();
            safeToTakePicture = true;
        } catch (Exception e) {
        }
        return camera;
    }

    Camera.PictureCallback mPicture = new Camera.PictureCallback(){
        @Override
        public void onPictureTaken(byte[] data, Camera camera){
            try{
                File mediaFile = getOutputMediaFile();

               /* View v1 =MainActivity.this.getWindow().getDecorView().getRootView();
                v1.setDrawingCacheEnabled(true);
                Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
                v1.setDrawingCacheEnabled(false);

                File imageFile = new File(String.valueOf(mediaFile));

                FileOutputStream outputStream = new FileOutputStream(imageFile);
                int quality = 30;
                bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
                try {
                    outputStream.flush();
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }*/



                if(mediaFile == null){
                    camera.startPreview();
                    safeToTakePicture = true;
                    globalMenuItem.findItem(R.id.menu_scan).setVisible(true);
                    globalMenuItem.findItem(R.id.menu_take_picture).setVisible(false);
                   return;
                }else{
                    globalMenuItem.findItem(R.id.menu_scan).setVisible(true);
                    globalMenuItem.findItem(R.id.menu_take_picture).setVisible(false);
                }
                FileOutputStream fos = null;
                try{
                   fos = new FileOutputStream(mediaFile);
                   fos.write(data);
                }catch(FileNotFoundException e){
                }catch(IOException e){
                }finally{
                    try{
                        fos.close();
                    }catch(IOException e){
                       e.printStackTrace();
                    }
                }
                release();
                data(mediaFile);
            }catch(NullPointerException np){
               np.printStackTrace();
            }
        }
    };
    private void data(final File mediaFile){
        if(connect) {
            //arrayList = new ArrayList<>();
            int id = 0;
            if (Total == 0){
               if(ScannerData.length() > 0) {
                   if(ScannerData.toLowerCase().contains("capture")){
                     Constants.getToast(MainActivity.this,"ReScan it again");
                   }else{
                       id = (int) Total + 1;
                       System.out.println("Id if ====>" + id);
                       final Model model = new Model();
                       model.setID(id);
                       model.setSKU(ScannerData);
                       model.setFILEPATH(mediaFile.toString());
                       model.setSTATUS(0);
                       arrayList.add(0, model);
                       //arrayList.add(model);
                       customAdapter = new CustomAdapter(this, arrayList);
                       list.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                       list.setAdapter(customAdapter);
                       customAdapter.notifyDataSetChanged();
                       Handler handler = new Handler();
                       final int finalId = id;
                       handler.postDelayed(new Runnable() {
                           public void run() {
                               if (Constants.isNetworkAvailable(MainActivity.this)) {
                                   dataBaseHelper.insertcamera(ScannerData, mediaFile.toString(), 0);
                                   NetworkCall(finalId, ScannerData, mediaFile.toString(), model);
                                   Total = dataBaseHelper.gettotalCount();
                                   System.out.println("Total if ===>" + Total);
                               } else {
                                   Constants.getToast(MainActivity.this, "Check your internet connection");
                               }
                           }
                       }, 100);
                       autotext.setText("");
                       autotext.clearFocus();
                       autotext.requestFocus();
                       autotext.setCursorVisible(true);
                       autotext.setFocusable(true);
                   }
               }
            } else {
                if (ScannerData.length() > 0) {
                    if(ScannerData.toLowerCase().contains("capture")) {
                        Constants.getToast(MainActivity.this,"ReScan it again");
                    }else{
                    id = (int) Total + 1;
                    final Model model = new Model();
                    model.setID(id);
                    model.setSKU(ScannerData);
                    model.setFILEPATH(mediaFile.toString());
                    model.setSTATUS(0);
                    System.out.println("Id else ====>"+id);
                    System.out.println("Id else ====>"+ScannerData);
                    System.out.println("Id else ====>"+mediaFile.toString());
                    arrayList.add(0, model);
                    //arrayList.add(model);
                    customAdapter.notifyDataSetChanged();
                    Handler handler = new Handler();
                    final int finalId = id;
                    handler.postDelayed(
                            new Runnable() {
                                public void run() {
                                    if(Constants.isNetworkAvailable(MainActivity.this)) {
                                        dataBaseHelper.insertcamera(ScannerData, mediaFile.toString(), 0);
                                        NetworkCall(finalId, ScannerData, mediaFile.toString(), model);
                                        Total = dataBaseHelper.gettotalCount();
                                        System.out.println("Total else ===>"+Total);
                                    }else{
                                        Constants.getToast(MainActivity.this,"Check your internet connection");
                                    }
                                }
                            }, 100);
                    autotext.setText("");
                    autotext.requestFocus();
                }
              }
            }
        }
        else {
            int id = 0;
            if (Total == 0){
                final String BarcodeValue1[] = BarcodeValue.split("Capture");
                System.out.println("Sku ===>"+BarcodeValue.toLowerCase());
                System.out.println("Sku ===>"+BarcodeValue1[0]);
                System.out.println("Sku ===>"+autotext.getText().toString());
                if (BarcodeValue1[0].length() > 0){
                    System.out.println("Sku ===>"+BarcodeValue.toLowerCase());
                    System.out.println("Sku ===>"+BarcodeValue1[0]);
                    arrayList = new ArrayList<>();
                    id = (int) Total + 1;
                    final Model model = new Model();
                    model.setID(id);
                    model.setSKU(BarcodeValue1[0]);
                    model.setFILEPATH(mediaFile.toString());
                    model.setSTATUS(0);
                    arrayList.add(0, model);
                    //arrayList.add(model);
                    customAdapter = new CustomAdapter(this, arrayList);
                    list.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                    list.setAdapter(customAdapter);
                    customAdapter.notifyDataSetChanged();
                    Handler handler = new Handler();
                    final int finalId = id;
                    handler.postDelayed(
                            new Runnable(){
                                public void run(){
                                    if(Constants.isNetworkAvailable(MainActivity.this)) {
                                        dataBaseHelper.insertcamera(BarcodeValue1[0].trim(), mediaFile.toString(), 0);
                                        Total = dataBaseHelper.gettotalCount();
                                        NetworkCall(finalId, BarcodeValue1[0].trim(), mediaFile.toString(), model);

                                    }else{
                                        Constants.getToast(MainActivity.this,"Check your internet connection");
                                    }
                                }
                            }, 500);
                    autotext.setText("");
                    autotext.clearFocus();
                    autotext.requestFocus();
                    autotext.setCursorVisible(true);
                    autotext.setFocusable(true);
                } else {
                    autotext.setText("");
                    autotext.clearFocus();
                    autotext.requestFocus();
                    autotext.setCursorVisible(true);
                    autotext.setFocusable(true);
                }
            } else {
                System.out.println("count ====>"+dataBaseHelper.gettotalCount());
                final String BarcodeValue1[] = BarcodeValue.split("Capture");
                if (BarcodeValue1[0].length() > 0) {
                    System.out.println("Sku ===>"+BarcodeValue.toLowerCase());
                    System.out.println("Sku ===>"+BarcodeValue1[0]);
                    id = (int) Total + 1;
                    final Model model = new Model();
                    model.setID(id);
                    model.setSKU(BarcodeValue1[0]);
                    model.setFILEPATH(mediaFile.toString());
                    model.setSTATUS(0);
                    arrayList.add(0, model);
                    //arrayList.add(model);
                    customAdapter.notifyDataSetChanged();
                    Handler handler = new Handler();
                    final int finalId = id;
                    handler.postDelayed(
                            new Runnable() {
                                public void run() {
                                    if(Constants.isNetworkAvailable(MainActivity.this)) {
                                      dataBaseHelper.insertcamera(BarcodeValue1[0].trim(), mediaFile.toString(), 0);
                                      NetworkCall(finalId, BarcodeValue1[0].trim(), mediaFile.toString(), model);
                                      Total = dataBaseHelper.gettotalCount();
                                    }else{
                                      Constants.getToast(MainActivity.this,"Check your internet connection");
                                    }
                                }
                            }, 500);
                    autotext.setText("");
                    autotext.requestFocus();
                } else {
                    autotext.setText("");
                    autotext.requestFocus();
                }
            }
        }
    }

    private File getOutputMediaFile(){
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()){
            if (!mediaStorageDir.mkdirs()){
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }


        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "RAM_" + timeStamp + ".jpg");
        System.out.println("MEDIA FILE ====>"+mediaFile);
        System.out.println("MEDIA FILE ====>"+autotext.getText().toString());
        return mediaFile;
    }

    class MyThread implements Runnable{
        @Override
        public void run(){
            Cursor c  =  dataBaseHelper.getData();
            if(c != null){
                if(c.moveToFirst()){
                    do{
                        if(c.getInt(c.getColumnIndex("status")) == 0){
                            Model model = new Model();
                            model.setID(c.getInt(c.getColumnIndex("_id")));
                            model.setSKU(c.getString(c.getColumnIndex("sku")));
                            model.setFILEPATH(c.getString(c.getColumnIndex("filename")));
                            model.setSTATUS(c.getInt(c.getColumnIndex("status")));
                            NetworkCall(c.getInt(c.getColumnIndex("_id")), c.getString(c.getColumnIndex("sku")), c.getString(c.getColumnIndex("filename")), model);
                        }//arrayList.add(model);
                    }while(c.moveToNext());
                }
            }
        }
    }
    private void release(){
        mCamera.release();
        image_layout.removeAllViews();
        take_priview();
    }
    public void updateDatabaseValues(){
        arrayList      = new ArrayList<>();
        Cursor c       = dataBaseHelper.getData();
        if(c != null){
            if(c.moveToFirst()){
                do{
                    System.out.println("Index value ===>"+c.getInt(c.getColumnIndex("_id")));
                    Model model = new Model();
                    model.setID(c.getInt(c.getColumnIndex("_id")));
                    model.setSKU(c.getString(c.getColumnIndex("sku")));
                    model.setFILEPATH(c.getString(c.getColumnIndex("filename")));
                    model.setSTATUS(c.getInt(c.getColumnIndex("status")));
                    System.out.println("Status ====>"+c.getString(c.getColumnIndex("status")));
                    arrayList.add(model);
                }while(c.moveToNext());
            }
        }
        customAdapter = new CustomAdapter(this,arrayList);
        list.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        list.setAdapter(customAdapter);
    }
    public void NetworkCall(final int id,final String autotext, final String storage,final Model mo){
        if(filesHashMap != null && filesHashMap.size() > 0){
          filesHashMap.clear();
        }
        //filesHashMap.put("" + System.currentTimeMillis(), new File(storage));
        HashMap<String, String> map = new HashMap<>();
        //map.put("barcode",     autotext);
        map.put("base64OfJpeg",storage);
        map.put("uploadedBy",  "GRCAPP");
        filesHashMap.put("" + System.currentTimeMillis(), new File(storage));
        new APICall1(Constants.URL + autotext, filesHashMap , map , this, new APICall1.APIRespose(){
            @Override
            public void onResponse(String result){
                if(result != null && !result.isEmpty()){
                    System.out.println("Merchant Data  =====>" + result);
                    System.out.println("Merchant Data  =====>" + id);
                    try{
                        JSONObject object = new JSONObject(result);
                        if(object.has("success")){
                            if(object.getString("message").equalsIgnoreCase("Success: Image Saved")){
                                try{
                                    System.out.println("success Id  "+id);
                                    if(dataBaseHelper.gettotalCount() > 0 ){
                                        dataBaseHelper.updatecamera(id,autotext, storage, 1);
                                        arrayList.remove(mo);
                                       /* dataBaseHelper.deleteContact(id);
                                        customAdapter.notifyDataSetChanged();*/
                                        Model model = new Model();
                                        model.setID(id);
                                        model.setSKU(autotext);
                                        model.setFILEPATH(storage);
                                        model.setSTATUS(1);
                                        arrayList.add(model);
                                        Collections.sort(arrayList, OrderbyID);
                                        customAdapter.notifyDataSetChanged();
                                    }
                                }catch(NullPointerException np){
                                    np.printStackTrace();
                                }
                            }
                        }
                    }catch(JSONException e) {
                      e.printStackTrace();
                    }
                }else{
                    Handler handler = new Handler();
                    handler.postDelayed(
                            new Runnable() {
                                public void run(){
                                    if(Constants.isNetworkAvailable(MainActivity.this)) {
                                        NetworkCall(id, autotext, storage, mo);
                                    }else{
                                        Constants.getToast(MainActivity.this,"Check your internet connection");
                                    }
                                }
                            }, 500);
                   Constants.getToast(MainActivity.this,"Else Case ");
                }
            }
        }).execute();
    }
}
