package cpm.com.gskmtorange.upload;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.os.AsyncTask;
import android.util.Log;

//import com.crashlytics.android.Crashlytics;
import com.google.gson.JsonSyntaxException;
import com.squareup.okhttp.MediaType;
import com.squareup.okhttp.MultipartBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Protocol;
import com.squareup.okhttp.RequestBody;

import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.MainActivity;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.retrofit.PostApiForFile;
import cpm.com.gskmtorange.retrofit.StringConverterFactory;
import cpm.com.gskmtorange.xmlGetterSetter.JourneyPlanGetterSetter;
import retrofit.GsonConverterFactory;
import retrofit.Retrofit;

/**
 * Created by yadavendras on 4/5/2018.
 */

public class UploadImageWithRetrofit {
    RequestBody body1;
    private Retrofit adapter;
    int status = 0;
    int count = 0;
    public static int uploadedFiles = 0;
    public static int totalFiles = 0;
    boolean isvalid = false, statusUpdated = true;
    Context context;
    String visitDate, userID, uploadStatus;
    int storeId = 0;
    GSKOrangeDB db;
    ProgressDialog pd;
    ArrayList<StoreBean> storeList, storeList_deviation, storeListAdditional, storeListPharma;
    private int factor, k = 0;
    Data data;


    public UploadImageWithRetrofit(String visitDate, String userId, Context context) {
        this.visitDate = visitDate;
        this.userID = userId;
        this.context = context;
        pd = new ProgressDialog(context);
        pd.setCancelable(false);
        pd.setTitle("Please wait");
        pd.setMessage("Uploading images");
        pd.show();
    }

    public void UploadImageRecursiveNew(final Context context) {
        try {
            status = 0;
            String filename = null, foldername = null;
            int totalfiles = 0;
            File f = new File(CommonString.getImagesFolder(context));
            File[] file = f.listFiles();
            assert file != null;
            count = file.length;
            if (file.length > 0) {
                filename = "";
                totalfiles = f.listFiles().length;
                pd.setMessage(context.getString(R.string.uploaddata) + " - " + context.getString(R.string.image) + " (" + uploadedFiles + "/" + totalFiles + ")");
                for (int i = 0; i < file.length; i++) {
                    if (new File(CommonString.getImagesFolder(context) + file[i].getName()).exists()) {
                        if (file[i].getName().contains("SI_") || file[i].getName().contains("CHK_SI_") || file[i].getName().contains("NonWorking")) {
                            foldername = "StoreImages";
                        } else if (file[i].getName().contains("GeoTag")) {
                            foldername = "GeotagImages";
                        } else if (file[i].getName().contains("T2P_Image")) {
                            foldername = "T2PImages";
                        } else if (file[i].getName().contains("AddPromo_Image") || file[i].getName().contains("Additional_Promo_Skuwise_Image")) {
                            foldername = "AdditionalPromotionImages";
                        } else if (file[i].getName().contains("AdditionalImage")) {
                            foldername = "AdditionalVisibilityImages";
                        } else if (file[i].getName().contains("Promo_Image")) {
                            foldername = "PromotionImages";
                        } else if (file[i].getName().contains("CategoryPicture")) {
                            foldername = "CategoryImages";
                        } else if (file[i].getName().contains("AuditAnsPic")) {
                            foldername = "AuditImages";
                        } else if (file[i].getName().contains("CoachingVisit") || file[i].getName().contains("CheckVisit")) {
                            foldername = "CoachingVisits";
                        } else if (file[i].getName().contains("DeliveryCalls")) {
                            foldername = "DeliveryCallsImages";
                        } else if (file[i].getName().contains("CounterfeitProduct")) {//added 15.04.2019
                            foldername = "CounterFeitImages";
                        } else if (file[i].getName().contains("POImage")) {//added 15.04.2019
                            foldername = "POImages";
                        }
                        else if (file[i].getName().contains("_IRPDIMG-")) {//added 15.04.2019
                            foldername = "IR_Images";
                        }
                        else if (file[i].getName().contains("_IRPD_VISI_IMG-")) {
                            foldername = "IR_VisibilityImages";
                        }
                        else {
                            foldername = "Bulkimages";
                        }
                        filename = file[i].getName();
                    }
                    break;
                }

                File originalFile = new File(CommonString.getImagesFolder(context) + filename);
                File finalFile = saveBitmapToFileSmaller(originalFile);
                if (finalFile == null) {
                    finalFile = originalFile;
                }

                OkHttpClient okHttpClient = new OkHttpClient();
                // okHttpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
                okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
                okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
                okHttpClient.setReadTimeout(20, TimeUnit.SECONDS);
                // MediaType mediaType = MediaType.parse("text/plain");

                RequestBody photo = RequestBody.create(MediaType.parse("application/octet-stream"), finalFile);
                body1 = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("file", finalFile.getName(), photo)
                        .addFormDataPart("FolderName", foldername)
                        .build();

                adapter = new Retrofit.Builder()
                        .baseUrl(CommonString.URL + "/")
                        .addConverterFactory(new StringConverterFactory())
                        .build();

                PostApiForFile api = adapter.create(PostApiForFile.class);
                retrofit.Call<String> call = api.getUploadImage(body1);
                File finalFile1 = finalFile;
                call.enqueue(new retrofit.Callback<String>() {
                    @Override
                    public void onResponse(retrofit.Response<String> response) {
                        Log.d("responsedata", String.valueOf(response));
                        if (response.isSuccess() && response.body().contains("Success")) {
                            finalFile1.delete();
                            status = 1;
                            uploadedFiles++;
                        } else {
                            status = 0;
                            //uploadedFiles = 0;
                        }
                        if (status == 0) {
                            pd.dismiss();
                            if (!((Activity) context).isFinishing()) {
                                showAlert((Activity) context, context.getString(R.string.DataNot), false);
                            }
                        } else {
                            UploadImageRecursiveNew(context);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) {
                            status = -1;
                            pd.dismiss();
                            Log.e("Errormsg :", t.toString());
                            if (!((Activity) context).isFinishing()) {
                                showAlert((Activity) context, context.getString(R.string.NetworkError), false);
                            }
                        }
                    }
                });


            } else {
                if (totalFiles == uploadedFiles) {
                    //region Coverage upload status Data
                    new StatusUpload().execute();
                }

            }
        } catch (JsonSyntaxException e) {
            e.fillInStackTrace();
            showAlert((Activity) context, "Invalid Json", false);
        } catch (Exception e) {
            e.fillInStackTrace();
            if (totalFiles == uploadedFiles) {
                showAlert((Activity) context, context.getString(R.string.data_uploaded_successfully), true);
            } else {
                showAlert((Activity) context, CommonString.KEY_FAILURE, false);
            }
        }
    }

    public void UploadDeliveryImageRecursive(final Context context, final ArrayList<String> file_list, final int index) {
        try {
            final int[] _index = {index};
            status = 0;
            String filename = null, foldername = "DeliveryCallsImages";

            if (_index[0] < file_list.size()) {
                filename = file_list.get(_index[0]);

                pd.setMessage(context.getString(R.string.uploaddata) + " - " + context.getString(R.string.image) + " (" + uploadedFiles + "/" + totalFiles + ")");

                File originalFile = new File(CommonString.getImagesFolder(context) + filename);
                File finalFile = saveBitmapToFileSmaller(originalFile);

                if (finalFile == null) {
                    finalFile = originalFile;
                }

                OkHttpClient okHttpClient = new OkHttpClient();
                okHttpClient.setConnectTimeout(20, TimeUnit.SECONDS);
                okHttpClient.setWriteTimeout(20, TimeUnit.SECONDS);
                okHttpClient.setReadTimeout(20, TimeUnit.SECONDS);

                com.squareup.okhttp.RequestBody photo = com.squareup.okhttp.RequestBody.create(com.squareup.okhttp.MediaType.parse("application/octet-stream"), finalFile);
                body1 = new MultipartBuilder()
                        .type(MultipartBuilder.FORM)
                        .addFormDataPart("file", finalFile.getName(), photo)
                        .addFormDataPart("FolderName", foldername)
                        .build();

                adapter = new retrofit.Retrofit.Builder()
                        .baseUrl(CommonString.URL + "/")
                        .addConverterFactory(new StringConverterFactory())
                        .build();
                PostApiForFile api = adapter.create(PostApiForFile.class);

                retrofit.Call<String> call = api.getUploadImage(body1);
                File finalFile1 = finalFile;
                call.enqueue(new retrofit.Callback<String>() {
                    @Override
                    public void onResponse(retrofit.Response<String> response) {
                        if (response.isSuccess() && response.body().contains("Success")) {
                            finalFile1.delete();
                            status = 1;
                            uploadedFiles++;
                        } else {
                            status = 0;
                            //uploadedFiles = 0;
                        }
                        if (status == 0) {
                            pd.dismiss();
                            if (!((Activity) context).isFinishing()) {
                                showAlert((Activity) context, context.getString(R.string.DataNot), false);
                            }
                        } else {
                            UploadDeliveryImageRecursive(context, file_list, ++_index[0]);
                        }
                    }

                    @Override
                    public void onFailure(Throwable t) {
                        if (t instanceof IOException || t instanceof SocketTimeoutException || t instanceof SocketException) {
                            status = -1;
                            //uploadedFiles = 0;
                            pd.dismiss();
                            // AlertandMessages.showAlert((Activity) context, "Network Error in upload", false);
                            if (!((Activity) context).isFinishing()) {
                                showAlert((Activity) context, context.getString(R.string.NetworkError), false);
                            }
                        }
                    }
                });


            } else {

                pd.dismiss();
                if (totalFiles == uploadedFiles) {
                    //region Coverage upload status Data
                    /*db = new GSKOrangeDB(context);
                    db.open();
                    db.updateDeliveryCallsUploadStatus();*/
                    //endregion
                    //pd.cancel();
                    //showAlert((Activity) context, context.getString(R.string.data_uploaded_successfully),true);
                }
                showAlert((Activity) context, context.getString(R.string.data_uploaded_successfully), true);
            }
        } catch (JsonSyntaxException e) {
            e.printStackTrace();
            showAlert((Activity) context, "Invalid Json", false);
        } catch (Exception e) {
            e.printStackTrace();
            if (totalFiles == uploadedFiles) {
                showAlert((Activity) context, context.getString(R.string.data_uploaded_successfully), true);
            } else {
                showAlert((Activity) context, CommonString.KEY_FAILURE, false);
            }
        }

    }

    public File saveBitmapToFileSmaller(File file) {
        File file2 = file;
        try {
            int inWidth = 0;
            int inHeight = 0;

            InputStream in = new FileInputStream(file2);
            // decode image size (decode metadata only, not the whole image)
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(in, null, options);
            in.close();
            in = null;

            // save width and height
            inWidth = options.outWidth;
            inHeight = options.outHeight;

            // decode full image pre-resized
            in = new FileInputStream(file2);
            options = new BitmapFactory.Options();
            // calc rough re-size (this is no exact resize)
            options.inSampleSize = Math.max(inWidth / 1632, inHeight / 1224);
            // decode full image
            Bitmap roughBitmap = BitmapFactory.decodeStream(in, null, options);
            if (roughBitmap == null) {
                return null;
            }

            // calc exact destination size
            Matrix m = new Matrix();
            RectF inRect = new RectF(0, 0, roughBitmap.getWidth(), roughBitmap.getHeight());
            RectF outRect = new RectF(0, 0, 1632, 1224);
            m.setRectToRect(inRect, outRect, Matrix.ScaleToFit.CENTER);
            float[] values = new float[9];
            m.getValues(values);
            // resize bitmap
            Bitmap resizedBitmap = Bitmap.createScaledBitmap(roughBitmap, (int) (roughBitmap.getWidth() * values[0]), (int) (roughBitmap.getHeight() * values[4]), true);
            // save image
            if (resizedBitmap == null) {
                return null;
            }
            FileOutputStream out = new FileOutputStream(file2);
            resizedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, out);

        } catch (Exception e) {
            Log.e("Image", e.toString(), e);
            return file;
        }
        return file2;
    }


    public void showAlert(final Context context, String str, final boolean flag) {

        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("Parinaam");
        builder.setMessage(str).setCancelable(false)
                .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Activity activity = (Activity) context;
                        if (flag) {
                            Intent i = new Intent(activity, MainActivity.class);
                            activity.startActivity(i);
                            activity.finish();

                        }

                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    public class StatusUpload extends AsyncTask<String, String, String> {

        @Override
        protected String doInBackground(String... strings) {

            try {
                db = new GSKOrangeDB(context);
                db.open();
                data = new Data();
                storeList = db.getStoreData(visitDate, CommonString.KEY_JOURNEY_PLAN);
                for (int i = 0; i < storeList.size(); i++) {
                    if (storeList.get(i).getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                        // SET COVERAGE STATUS
                        String final_xml = "";
                        String onXML = "";
                        onXML = "[COVERAGE_STATUS]"
                                + "[STORE_ID]" + storeList.get(i).getSTORE_ID() + "[/STORE_ID]"
                                + "[VISIT_DATE]" + storeList.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[USER_ID]" + userID + "[/USER_ID]"
                                + "[STATUS]" + CommonString.KEY_U + "[/STATUS]"
                                + "[/COVERAGE_STATUS]";

                        final_xml = final_xml + onXML;

                        final String sos_xml = "[DATA]" + final_xml + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_COVERAGE_STATUS);
                        request.addProperty("onXML", sos_xml);

                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);

                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_COVERAGE_STATUS, envelope);

                        Object result = envelope.getResponse();

                        //If Result is success then status of that store is update
                        if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {

                            db.open();

                            final CoverageBean coverageObj = db.getCoverageSpecificData(storeList.get(i).getVISIT_DATE(), storeList.get(i).getSTORE_ID());

                            String uploadStatus;
                            if (coverageObj.getReasonid().equalsIgnoreCase("0")) {
                                uploadStatus = CommonString.KEY_U;
                            } else {
                                uploadStatus = CommonString.KEY_UN;
                            }

                            db.updateCoverageStatus(storeList.get(i).getSTORE_ID(), uploadStatus);
                            db.updateStoreStatusOnLeave(storeList.get(i).getSTORE_ID(), storeList.get(i).getVISIT_DATE(),
                                    uploadStatus, CommonString.FROM_JCP);

                            db.deleteTableWithStoreID(storeList.get(i).getSTORE_ID());
                        }

                    }
                }

                db.open();
                storeList_deviation = db.getStoreData(visitDate, CommonString.KEY_ADHOC_JOURNEY_PLAN);
                for (int i = 0; i < storeList_deviation.size(); i++) {
                    if (storeList_deviation.get(i).getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                        // SET COVERAGE STATUS
                        String final_xml = "";
                        String onXML = "";
                        onXML = "[COVERAGE_STATUS]"
                                + "[STORE_ID]" + storeList_deviation.get(i).getSTORE_ID() + "[/STORE_ID]"
                                + "[VISIT_DATE]" + storeList_deviation.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[USER_ID]" + userID + "[/USER_ID]"
                                + "[STATUS]" + CommonString.KEY_U + "[/STATUS]"
                                + "[/COVERAGE_STATUS]";

                        final_xml = final_xml + onXML;

                        final String sos_xml = "[DATA]" + final_xml + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_COVERAGE_STATUS);
                        request.addProperty("onXML", sos_xml);

                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);

                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_COVERAGE_STATUS, envelope);

                        Object result = envelope.getResponse();

                        //If Result is success then status of that store is update
                        if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {

                            db.open();
                            db.updateCoverageStatus(storeList_deviation.get(i).getSTORE_ID(), CommonString.KEY_U);
                            db.updateStoreStatusOnLeave(storeList_deviation.get(i).getSTORE_ID(), storeList_deviation.get(i).getVISIT_DATE(),
                                    CommonString.KEY_U, CommonString.KEY_ADHOC_JOURNEY_PLAN);

                            db.deleteTableWithStoreID(storeList_deviation.get(i).getSTORE_ID());
                        }

                    }
                }

                //for Turkey Pharma Stores
                storeListPharma = db.getStoreData(visitDate, CommonString.KEY_JOURNEY_PLAN_PHARMA);
                for (int i = 0; i < storeListPharma.size(); i++) {
                    if (storeListPharma.get(i).getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                        // SET COVERAGE STATUS
                        String final_xml = "";
                        String onXML = "";
                        onXML = "[COVERAGE_STATUS]"
                                + "[STORE_ID]" + storeListPharma.get(i).getSTORE_ID() + "[/STORE_ID]"
                                + "[VISIT_DATE]" + storeListPharma.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[USER_ID]" + userID + "[/USER_ID]"
                                + "[STATUS]" + CommonString.KEY_U + "[/STATUS]"
                                + "[/COVERAGE_STATUS]";

                        final_xml = final_xml + onXML;

                        final String sos_xml = "[DATA]" + final_xml + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_COVERAGE_STATUS_PHARMA);
                        request.addProperty("onXML", sos_xml);

                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);

                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_COVERAGE_STATUS_PHARMA, envelope);

                        Object result = envelope.getResponse();

                        //If Result is success then status of that store is update
                        if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {

                            db.open();

                            final CoverageBean coverageObj = db.getCoverageSpecificData(storeListPharma.get(i).getVISIT_DATE(), storeListPharma.get(i).getSTORE_ID());

                            String uploadStatus;
                            if (coverageObj.getReasonid().equalsIgnoreCase("0")) {
                                uploadStatus = CommonString.KEY_U;
                            } else {
                                uploadStatus = CommonString.KEY_UN;
                            }

                            db.updateCoverageStatus(storeListPharma.get(i).getSTORE_ID(), uploadStatus);
                            db.updateStoreStatusOnLeave(storeListPharma.get(i).getSTORE_ID(), storeListPharma.get(i).getVISIT_DATE(),
                                    uploadStatus, CommonString.FROM_PHARMA);

                            db.deleteTableWithStoreID(storeListPharma.get(i).getSTORE_ID());
                        }

                    }
                }

                //Additional Stores Egypt
                storeListAdditional = db.getStoreData(visitDate, CommonString.KEY_JOURNEY_PLAN_ADDITIONAL);
                for (int i = 0; i < storeListAdditional.size(); i++) {
                    if (storeListAdditional.get(i).getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                        // SET COVERAGE STATUS
                        String final_xml = "";
                        String onXML = "";
                        onXML = "[COVERAGE_STATUS]"
                                + "[STORE_ID]" + storeListAdditional.get(i).getSTORE_ID() + "[/STORE_ID]"
                                + "[VISIT_DATE]" + storeListAdditional.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[USER_ID]" + userID + "[/USER_ID]"
                                + "[STATUS]" + CommonString.KEY_U + "[/STATUS]"
                                + "[/COVERAGE_STATUS]";

                        final_xml = final_xml + onXML;

                        final String sos_xml = "[DATA]" + final_xml + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_COVERAGE_STATUS_ADDITIONAL);
                        request.addProperty("onXML", sos_xml);

                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);

                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_COVERAGE_STATUS_ADDITIONAL, envelope);

                        Object result = envelope.getResponse();

                        //If Result is success then status of that store is update
                        if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {

                            db.open();

                            final CoverageBean coverageObj = db.getCoverageSpecificData(storeListAdditional.get(i).getVISIT_DATE(), storeListAdditional.get(i).getSTORE_ID());

                            String uploadStatus;
                            if (coverageObj.getReasonid().equalsIgnoreCase("0")) {
                                uploadStatus = CommonString.KEY_U;
                            } else {
                                uploadStatus = CommonString.KEY_UN;
                            }

                            db.updateCoverageStatus(storeListAdditional.get(i).getSTORE_ID(), uploadStatus);
                            db.updateStoreStatusOnLeave(storeListAdditional.get(i).getSTORE_ID(), storeListAdditional.get(i).getVISIT_DATE(),
                                    uploadStatus, CommonString.FROM_ADDITIONAL);
                            db.deleteTableWithStoreID(storeListAdditional.get(i).getSTORE_ID());
                        }

                    }
                }

                //Additional Adhoc Stores Egypt
                storeListAdditional = db.getStoreData(visitDate, CommonString.KEY_ADHOC_JOURNEYPLAN_ADDITIONAL);
                for (int i = 0; i < storeListAdditional.size(); i++) {
                    if (storeListAdditional.get(i).getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                        // SET COVERAGE STATUS
                        String final_xml = "";
                        String onXML = "";
                        onXML = "[COVERAGE_STATUS]"
                                + "[STORE_ID]" + storeListAdditional.get(i).getSTORE_ID() + "[/STORE_ID]"
                                + "[VISIT_DATE]" + storeListAdditional.get(i).getVISIT_DATE() + "[/VISIT_DATE]"
                                + "[USER_ID]" + userID + "[/USER_ID]"
                                + "[STATUS]" + CommonString.KEY_U + "[/STATUS]"
                                + "[/COVERAGE_STATUS]";

                        final_xml = final_xml + onXML;

                        final String sos_xml = "[DATA]" + final_xml + "[/DATA]";

                        SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_UPLOAD_COVERAGE_STATUS_ADDITIONAL);
                        request.addProperty("onXML", sos_xml);

                        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
                        envelope.dotNet = true;
                        envelope.setOutputSoapObject(request);

                        HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                        androidHttpTransport.call(CommonString.SOAP_ACTION + CommonString.METHOD_UPLOAD_COVERAGE_STATUS_ADDITIONAL, envelope);

                        Object result = envelope.getResponse();

                        //If Result is success then status of that store is update
                        if (result.toString().equalsIgnoreCase(CommonString.KEY_SUCCESS)) {

                            db.open();

                            final CoverageBean coverageObj = db.getCoverageSpecificData(storeListAdditional.get(i).getVISIT_DATE(), storeListAdditional.get(i).getSTORE_ID());

                            String uploadStatus;
                            if (coverageObj.getReasonid().equalsIgnoreCase("0")) {
                                uploadStatus = CommonString.KEY_U;
                            } else {
                                uploadStatus = CommonString.KEY_UN;
                            }

                            db.updateCoverageStatus(storeListAdditional.get(i).getSTORE_ID(), uploadStatus);
                            db.updateStoreStatusOnLeave(storeListAdditional.get(i).getSTORE_ID(), storeListAdditional.get(i).getVISIT_DATE(),
                                    uploadStatus, CommonString.FROM_ADDITIONAL_ADHOC);

                            db.deleteTableWithStoreID(storeListAdditional.get(i).getSTORE_ID());
                        }

                    }
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                // Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                // Crashlytics.logException(e.getCause());
                // Crashlytics.logException(new Exception(e.getCause()));
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            } catch (Exception e) {
                // Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                // Crashlytics.logException(e.getCause());
                // Crashlytics.logException(new Exception(e.getCause()));
                e.printStackTrace();
            }
            if (statusUpdated) {
                return CommonString.KEY_SUCCESS;
            } else {
                return CommonString.KEY_FAILURE;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            pd.dismiss();
            if (s.equalsIgnoreCase(CommonString.KEY_SUCCESS)) {
                if (totalFiles == uploadedFiles) {
                    showAlert((Activity) context, context.getString(R.string.data_uploaded_successfully), true);
                } else {
                    showAlert((Activity) context, context.getString(R.string.DataNot), true);
                }
            }
        }
    }

    class Data {
        int value;
        String name;
    }
}
