package cpm.com.gskmtorange.dailyentry;

import static com.google.android.gms.location.LocationRequest.Builder.IMPLICIT_MIN_UPDATE_INTERVAL;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

//import com.crashlytics.android.Crashlytics;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.cardview.widget.CardView;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.location.Priority;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Locale;

import cpm.com.gskmtorange.Database.GSKOrangeDB;
import cpm.com.gskmtorange.GeoTag.GeoTagActivity;
import cpm.com.gskmtorange.GetterSetter.CategoryPictureGetterSetter;
import cpm.com.gskmtorange.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.GetterSetter.GeotaggingBeans;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.adapter.data.ImageUri;
import cpm.com.gskmtorange.comparators.StatusCompare;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.constant.CommonUtils;
import cpm.com.gskmtorange.download.DownloadActivity;
import cpm.com.gskmtorange.gsk_dailyentry.StoreWisePerformanceActivity;
import cpm.com.gskmtorange.pharma_stores.PharmaActivity;
import cpm.com.gskmtorange.storeinmap.StoreListMapActivity;
import cpm.com.gskmtorange.storeinmap.StoreListRouteActivity;
import cpm.com.gskmtorange.storeinmap.StoreRouteActivity;
import cpm.com.gskmtorange.xmlGetterSetter.ADDITIONAL_DISPLAY_MASTERGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.AdditionalQuestiongetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.BrandMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.CategoryMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationContrywiseGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.DisplayChecklistMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.DisplayMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.GeoFencingGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.JourneyPlanGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPINGT2PGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPING_ADDITIONAL_PROMOTION_MasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPING_PLANOGRAM_MasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MAPPING_SOS_TARGET_MasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingCategoryImageAllowGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingDisplayChecklistGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingPlanogramCountrywiseGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingPlanogramStorewiseGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingPromotionGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingStockGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingStockStorewiseGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.MappingSubCategoryImageAllowGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NoCameraLastVisitGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NonT2pReasonGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NonWorkingReasonGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.NonWorkingSubReasonGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.POGQuestionGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.STORE_PERFORMANCE_MasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.ShelfMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SkuGroupMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.SupervisorListGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.TableBean;
import cpm.com.gskmtorange.xmlGetterSetter.Visit_Type_Master_GetterSetter;
import cpm.com.gskmtorange.xmlHandlers.XMLHandlers;

public class StoreListActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
    ArrayList<CoverageBean> coverage = new ArrayList<CoverageBean>();
    ArrayList<StoreBean> storelist = new ArrayList<StoreBean>();
    //ListView list;
    private SharedPreferences preferences;
    String date, visit_status;
    GSKOrangeDB db;
    StoreListActivity.ValueAdapter adapter;
    RecyclerView recyclerView;
    private SharedPreferences.Editor editor = null;
    LinearLayout linearlay;
    String store_id, userId, culture_id, visit_date, store_facing_hide;
    private Dialog dialog;
    boolean result_flag = false, leaveflag = false;
    FloatingActionButton fab;
    //String storeid;
    Toolbar toolbar;
    String language, country_id;
    String store_flag_str;

    Context context;
    boolean enabled = true;
    GoogleApiClient mGoogleApiClient;
    double lat = 0.0, lon = 0.0;
    private LocationManager locmanager = null;
    ArrayList<GeotaggingBeans> geolist;
    //ArrayList<GeoPhencingGetterSetter> geoPhenceGetSet;
    int distanceGeoPhence = 500;
    private static int UPDATE_INTERVAL = 200; // 5 sec
    private static int FATEST_INTERVAL = 100; // 1 sec
    private static int DISPLACEMENT = 1; // 10 meters
    private static final int REQUEST_LOCATION = 1;
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 1000;
    private Location mLastLocation;
    private LocationRequest mLocationRequest;

    ArrayList<GeoFencingGetterSetter> geoFencingGetterSetters;

    //New Location changes
    private FusedLocationProviderClient fusedLocationProviderClient;
    LocationRequest locationRequest;

    DisplayMasterGetterSetter displayMasterGetterSetter;
    MappingStockGetterSetter mappingStockGetterSetter;
    MappingStockStorewiseGetterSetter mappingStockStorewiseGetterSetter;
    MAPPINGT2PGetterSetter mappingt2PGetterSetter;
    DisplayChecklistMasterGetterSetter checklistMasterGetterSetter;
    MappingDisplayChecklistGetterSetter mappingChecklistGetterSetter;
    NonWorkingReasonGetterSetter nonWorkingReasonGetterSetter;
    MappingPromotionGetterSetter mappingPromotionGetterSetter;
    MAPPING_ADDITIONAL_PROMOTION_MasterGetterSetter mapping_additional_promotion_masterGetterSetter;
    STORE_PERFORMANCE_MasterGetterSetter store_performance_masterGetterSetter;
    ADDITIONAL_DISPLAY_MASTERGetterSetter additional_display_getter_setter;
    MAPPING_SOS_TARGET_MasterGetterSetter mapping_sos_target_masterGetterSetter;
    MAPPING_PLANOGRAM_MasterGetterSetter mapping_planogram_masterGetterSetter;
    ShelfMasterGetterSetter shelfMasterGetterSetter;
    MappingSubCategoryImageAllowGetterSetter mappingSubCategoryImageAllowGetterSetter;
    MappingCategoryImageAllowGetterSetter mappingCategoryImageAllowGetterSetter;
    SkuGroupMasterGetterSetter skuGroupMasterGetterSetter;
    AdditionalQuestiongetterSetter additionalQuestiongetterSetter;
    POGQuestionGetterSetter pogQuestionGetterSetter;
    NonT2pReasonGetterSetter nonT2pReasonGetterSetter;
    ConfigurationContrywiseGetterSetter configurationContrywiseGetterSetter;
    NoCameraLastVisitGetterSetter noCameraLastVisitGetterSetter;
    NonWorkingSubReasonGetterSetter nonWorkingSubReasonGetterSetter;
    SupervisorListGetterSetter supervisorListGetterSetter;
    ConfigurationMasterGetterSetter configurationMasterGetterSetter;
    MappingPlanogramStorewiseGetterSetter mappingPlanogramStorewiseGetterSetter;
    private ProgressBar pb;
    private TextView percentage, message;

    Data data;
    int eventType;
    boolean ResultFlag = true;
    String str;
    StoreBean storeCurrentObj;

    String from_checkedIn = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.storelistfablayout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);


        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        context = this;
        fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));

        store_flag_str = getIntent().getStringExtra(CommonString.KEY_STORE_FLAG);

        date = preferences.getString(CommonString.KEY_DATE, null);
        visit_status = preferences.getString(CommonString.KEY_STOREVISITED_STATUS, "");
        language = preferences.getString(CommonString.KEY_LANGUAGE, "");
        country_id = preferences.getString(CommonString.KEY_COUNTRY_ID, "");
        userId = preferences.getString(CommonString.KEY_USERNAME, null);
        culture_id = preferences.getString(CommonString.KEY_CULTURE_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, null);
        db = new GSKOrangeDB(StoreListActivity.this);
        db.open();

        linearlay = (LinearLayout) findViewById(R.id.no_data_lay);
        recyclerView = (RecyclerView) findViewById(R.id.drawer_layout_recycle);

        fab = (FloatingActionButton) findViewById(R.id.fab);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent in = new Intent(context, DownloadActivity.class);
                startActivity(in);
                finish();
            }
        });

        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(context, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }

        if (checkPlayServices()) {
            // Building the GoogleApi client
            buildGoogleApiClient();

            createLocationRequest();
        }

        // Create an instance of GoogleAPIClient.
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(this).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        }

       // deleteIRURl();
    }

    private void deleteIRURl() {
        try {
            ArrayList<CategoryPictureGetterSetter> irList = db.getIrPDforUpload("44912", visit_date);
            if (irList != null && !irList.isEmpty()) {
                for (int i = 0; i < irList.size(); i++) {
                    ArrayList<ImageUri> uris = irList.get(i).getImageUris();
                    if (uris != null && !uris.isEmpty()) {
                        for (int k = 0; k < uris.size(); k++) {
                            CommonUtils.INSTANCE.deleteSpecificImage(this,uris.get(k).getUri());
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    private boolean checkPlayServices() {
        int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
        if (resultCode != ConnectionResult.SUCCESS) {
            if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
                GooglePlayServicesUtil.getErrorDialog(resultCode, this, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Toast.makeText(context, getResources().getString(R.string.notsuppoted), Toast.LENGTH_LONG).show();
                finish();
            }
            return false;
        }
        return true;
    }

    protected synchronized void buildGoogleApiClient() {
        if (mGoogleApiClient == null) {
            mGoogleApiClient = new GoogleApiClient.Builder(context).addConnectionCallbacks(this).addOnConnectionFailedListener(this).addApi(LocationServices.API).build();
        }
    }

    protected void createLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FATEST_INTERVAL);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest.setSmallestDisplacement(DISPLACEMENT);
    }

    @Override
    public void onConnectionSuspended(int i) {
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

        // Toast.makeText(this,  " WORKS_lat_lon " + latLng, Toast.LENGTH_LONG).show();
        //  updateLocation(latLng);
        if (mGoogleApiClient != null) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
        }
    }

    protected void startLocationUpdates() {
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mGoogleApiClient != null) {
                LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
            }
        }
    }

    public static int distFrom(double lat1, double lng1, double lat2, double lng2) {
        double earthRadius = 6371000; //meters
        double dLat = Math.toRadians(lat2 - lat1);
        double dLng = Math.toRadians(lng2 - lng1);
        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        int dist = (int) (earthRadius * c);

        return dist;
    }

    @Override
    public void onConnected(Bundle bundle) {
       /* if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            if (mLastLocation != null) {
                lat = mLastLocation.getLatitude();
                lon = mLastLocation.getLongitude();

            }
            startLocationUpdates();
        }*/
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    protected void onStart() {
        super.onStart();
        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
    }

    private boolean checkgpsEnableDevice() {
        boolean flag = true;
        if (!hasGPSDevice(context)) {
            Toast.makeText(context, "Gps not Supported", Toast.LENGTH_SHORT).show();
        }
        final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            enableLoc();
            flag = false;
        } else if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER) && hasGPSDevice(context)) {
            flag = true;
        }
        return flag;
    }

    private boolean hasGPSDevice(Context context) {
        final LocationManager mgr = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        if (mgr == null) return false;
        final List<String> providers = mgr.getAllProviders();
        if (providers == null) return false;
        return providers.contains(LocationManager.GPS_PROVIDER);
    }

    private void enableLoc() {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        locationRequest.setInterval(30 * 1000);
        locationRequest.setFastestInterval(5 * 1000);
        LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
        builder.setAlwaysShow(true);
        if (mGoogleApiClient != null) {
            PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
            result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
                @Override
                public void onResult(LocationSettingsResult result) {
                    final Status status = result.getStatus();
                    switch (status.getStatusCode()) {
                        case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                            try {
                                // Show the dialog by calling startResolutionForResult(),
                                // and check the result in onActivityResult().
                                status.startResolutionForResult((Activity) context, REQUEST_LOCATION);
                            } catch (IntentSender.SendIntentException e) {
                                // Ignore the error.
                            }
                            break;
                    }
                }
            });
        }
    }

    public void GPSAlert() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
        alertDialog.setTitle("GPS IS DISABLED...");
        alertDialog.setMessage("Click ok to enable GPS.");
        alertDialog.setCancelable(false);
        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                startActivity(intent);
                dialog.dismiss();
            }
        });
        alertDialog.show();
    }


    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        if (mGoogleApiClient != null) {
            mGoogleApiClient.connect();
        }
        checkgpsEnableDevice();

        locationRequest = new LocationRequest.Builder(Priority.PRIORITY_HIGH_ACCURACY, 100000).setWaitForAccurateLocation(false).setMinUpdateIntervalMillis(IMPLICIT_MIN_UPDATE_INTERVAL).setMaxUpdateDelayMillis(1000).build();


        LocationCallback locationCallback = new LocationCallback() {
            @Override
            public void onLocationResult(LocationResult locationResult) {
                if (locationResult != null) {
                    if (locationResult == null) {
                        return;
                    }
                    //Showing the latitude, longitude and accuracy on the home screen.
                    for (Location location : locationResult.getLocations()) {
                        lat = location.getLatitude();
                        lon = location.getLongitude();
                        // Log.e("latitude_inside",location.getLatitude() + "," +location.getLongitude());
                    }
                }
            }
        };
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(StoreListActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 1);
            ActivityCompat.requestPermissions(StoreListActivity.this, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, 2);
        }
        fusedLocationProviderClient.requestLocationUpdates(locationRequest, locationCallback, Looper.getMainLooper());


        CommonFunctions.updateLangResources(context, preferences.getString(CommonString.KEY_LANGUAGE, ""));
        //toolbar.setTitle(getString(R.string.title_activity_store_list));
        // Log.e("storeflag",store_flag_str);
        db.open();
        if (store_flag_str.equals(CommonString.FROM_JCP)) {
            toolbar.setTitle(getString(R.string.title_activity_store_list));
            storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN);
        } else if (store_flag_str.equals(CommonString.FROM_ADDITIONAL)) {
            //Additional Journey Plan - Egypt
            toolbar.setTitle(getString(R.string.title_activity_store_list));
            storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN_ADDITIONAL);
        } else if (store_flag_str.equals(CommonString.FROM_PHARMA)) {
            //Pharma stores - Turkey
            toolbar.setTitle(getString(R.string.title_activity_store_list));
            storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN_PHARMA);
        } else if (store_flag_str.equals(CommonString.FROM_ADDITIONAL_ADHOC)) {
            //Additional Journey Plan - Egypt
            toolbar.setTitle(getString(R.string.title_activity_store_list));
            storelist = db.getStoreData(date, CommonString.KEY_ADHOC_JOURNEYPLAN_ADDITIONAL);
        } else {
            toolbar.setTitle(getString(R.string.adhoc_store_list));
            storelist = db.getStoreData(date, CommonString.KEY_ADHOC_JOURNEY_PLAN);
            //fab.setVisibility(View.GONE);
        }

        coverage = db.getCoverageData(date, store_flag_str);

        geoFencingGetterSetters = db.getGeoFencing(country_id);


        if (storelist.size() > 0) {
            //list.setAdapter(new MyAdaptor());
            StatusCompare ratingCompare = new StatusCompare();
            Collections.sort(storelist, ratingCompare);

            adapter = new StoreListActivity.ValueAdapter(context, storelist);
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(this));

        } else {

            recyclerView.setVisibility(View.INVISIBLE);
            linearlay.setVisibility(View.VISIBLE);
            if (store_flag_str.equals(CommonString.FROM_JCP)) {
                fab.show();//setVisibility(View.VISIBLE);
            }

        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);
    }

   /* @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.sorelist_menu, menu);

        // return true so that the menu pop up is opened
        return true;
    }*/

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();


        if (id == android.R.id.home) {

            // NavUtils.navigateUpFromSameTask(this);
            finish();


            overridePendingTransition(R.anim.activity_back_in, R.anim.activity_back_out);

        } else if (id == R.id.iconMap) {

            Intent in = new Intent(context, StoreListRouteActivity.class);
            in.putExtra(CommonString.KEY_STORE_LIST, storelist);
            startActivity(in);
        }

        return super.onOptionsItemSelected(item);
    }


    private class ValueAdapter extends RecyclerView.Adapter<StoreListActivity.ValueAdapter.MyViewHolder> {
        private LayoutInflater inflator;
        List<StoreBean> data = Collections.emptyList();

        public ValueAdapter(Context context, List<StoreBean> data) {
            inflator = LayoutInflater.from(context);
            this.data = data;

        }

        @NonNull
        @Override
        public StoreListActivity.ValueAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int i) {
            View view = inflator.inflate(R.layout.storelist_child, parent, false);
            return new MyViewHolder(view);
        }

        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final StoreListActivity.ValueAdapter.MyViewHolder viewHolder, final int position) {
            final StoreBean current = data.get(position);
            if (language.equalsIgnoreCase("TURKISH")) {
                viewHolder.chkbtn.setBackgroundResource(R.mipmap.checkout_turkish);
            } else {
                viewHolder.chkbtn.setBackgroundResource(R.mipmap.checkout);
            }

            final String storeid = current.getSTORE_ID();
            final CoverageBean coverageObj = db.getCoverageSpecificData(date, storeid);

            viewHolder.txt.setText(current.getSTORE_NAME() + "(" + current.getSTORE_ID() + ")");
            viewHolder.address.setText(current.getADDRESS());

            if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_U)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.tick);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_UN)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.tick_close);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getCHECKOUT_STATUS().equalsIgnoreCase(CommonString.KEY_Y)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_P)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_L)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation_close);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE)) {

                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation_close);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else if (coverageObj.getStatus() != null && coverageObj.getStatus().equalsIgnoreCase(CommonString.KEY_VALID)) {
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
                viewHolder.chkbtn.setVisibility(View.VISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.imageview.setVisibility(View.INVISIBLE);
            } else if (coverageObj.getStatus() != null && coverageObj.getStatus().equalsIgnoreCase(CommonString.KEY_INVALID)) {
                viewHolder.imageview.setVisibility(View.INVISIBLE);
                viewHolder.chkbtn.setVisibility(View.GONE);
                viewHolder.cancel_btn.setVisibility(View.VISIBLE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.green));

            } else if (coverageObj.getStatus() != null && coverageObj.getStatus().equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE)) {

                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation_close);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
            } else {
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
                viewHolder.imageview.setVisibility(View.INVISIBLE);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
            }

            if (current.getGEO_TAG().equalsIgnoreCase("N")) {
                viewHolder.imgview_navigation.setVisibility(View.INVISIBLE);
            } else {
                viewHolder.imgview_navigation.setVisibility(View.VISIBLE);
            }


            viewHolder.parent_layout.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    store_id = current.getSTORE_ID();
                    store_facing_hide = current.getFACING_HIDE();
                    storeCurrentObj = current;

                    if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_U) || current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_UN)) {
                        Snackbar.make(v, R.string.title_store_list_activity_store_already_done, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_D)) {

                        Snackbar.make(v, R.string.title_store_list_activity_store_data_uploaded, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    } else if (current.getCHECKOUT_STATUS().equalsIgnoreCase(CommonString.KEY_Y)) {

                        Snackbar.make(v, R.string.title_store_list_activity_store_already_checkout, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                    } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_P)) {

                        Snackbar.make(v, R.string.title_store_list_activity_store_again_uploaded, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_L)) {
                        Snackbar.make(v, R.string.title_store_list_activity_store_closed, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    } else if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE)) {
                        Snackbar.make(v, R.string.title_store_list_activity_already_store_closed, Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    } else if (checkleavestatus(store_id)) {

                        Snackbar.make(v, R.string.title_store_list_activity_already_store_closed, Snackbar.LENGTH_LONG).setAction("Action", null).show();

                    } else {
                        // PUT IN PREFERENCES
                        if (checkotherCheckedIn(store_flag_str)) {
                            Snackbar.make(v, getString(R.string.title_store_list_checkout_current) + " - " + from_checkedIn, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                        } else {
                            if (!setCheckedMethod(store_id)) {
                                boolean enteryflag = true;
                                if (coverage.size() > 0) {
                                    int i;
                                    for (i = 0; i < coverage.size(); i++) {

                                        if (coverage.get(i).getInTime() != null) {

                                            if (coverage.get(i).getOutTime() == null) {
                                                if (!store_id.equals(coverage.get(i).getStoreId())) {
                                                    Snackbar.make(v, R.string.title_store_list_checkout_current, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                                    enteryflag = false;
                                                }
                                                break;
                                            }
                                        }
                                    }
                                }

                                if (enteryflag) {
                                    if (store_flag_str.equals(CommonString.FROM_PHARMA) && coverageObj.getStatus() != null && coverageObj.getStatus().equalsIgnoreCase(CommonString.KEY_VALID)) {
                                        Snackbar.make(v, R.string.title_store_list_checkout_Already_filled, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                    } /*if((store_flag_str.equals(CommonString.FROM_ADDITIONAL_ADHOC) || store_flag_str.equals(CommonString.FROM_ADDITIONAL)) && coverageObj.getStatus()!=null && coverageObj.getStatus().equalsIgnoreCase(CommonString.KEY_VALID)){
                                        Snackbar.make(v, R.string.title_store_list_checkout_Already_filled, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                    }*/ else if (store_flag_str.equals(CommonString.FROM_JCP) || store_flag_str.equals(CommonString.FROM_PHARMA) || store_flag_str.equals(CommonString.FROM_ADDITIONAL_ADHOC) || store_flag_str.equals(CommonString.FROM_ADDITIONAL)) {
                                        showMyDialog(store_id, current.getSTORE_NAME(), "Yes", current.getVISIT_DATE(), current.getCHECKOUT_STATUS(), current.getGEO_TAG(), current);
                                    } else {
                                        if (country_id.equalsIgnoreCase("5") || country_id.equalsIgnoreCase("15") || country_id.equalsIgnoreCase("2") || country_id.equalsIgnoreCase(CommonString.COUNTRY_ID_EGYPT + "")) {
                                            if (!current.getGEO_TAG().equalsIgnoreCase("N")) {
                                                boolean flag = true;
                                                if (coverage.size() > 0) {
                                                    for (int i = 0; i < coverage.size(); i++) {
                                                        if (store_id.equals(coverage.get(i).getStoreId())) {
                                                            flag = false;
                                                            break;
                                                        }
                                                    }
                                                }
                                                boolean flag_entry = true;
                                                int distance = 0;
                                                //geo fencing enabled only if GEO_FENCING equals 1 for COUNTRY_ID
                                                if (flag && geoFencingGetterSetters.size() > 0 && geoFencingGetterSetters.get(0).getGEO_FENCING().get(0).equals("1")) {
                                                    distanceGeoPhence = Integer.parseInt(geoFencingGetterSetters.get(0).getDISTANCE_MTR().get(0));

                                                    double store_lat = Double.parseDouble(current.getLATITUDE());
                                                    double store_lon = Double.parseDouble(current.getLONGITUDE());

                                                    if (store_lat != 0.0 && store_lon != 0.0) {
                                                        distance = distFrom(store_lat, store_lon, lat, lon);

                                                        if (distance > distanceGeoPhence) {
                                                            flag_entry = false;
                                                        } else {
                                                            String msg = getString(R.string.distance_from_the_store) + " " + distance + " meters";
                                                            Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                }

                                                if (flag_entry) {
                                                    // Log.e("flag_entrydata","flagdata");
                                                    editor = preferences.edit();
                                                    editor.putString(CommonString.KEY_STORE_FLAG, store_flag_str);
                                                    editor.putString(CommonString.KEY_STORE_FLAG_FACING_HIDE, current.getFACING_HIDE());
                                                    editor.putString(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                                                    editor.putString(CommonString.KEY_STORE_NAME, current.getSTORE_NAME());
                                                    editor.putString(CommonString.KEY_VISIT_DATE, current.getVISIT_DATE());
                                                    editor.putString(CommonString.KEY_CAMERA_ALLOW, current.getCAMERA_ALLOW());
                                                    editor.putString(CommonString.KEY_CHECKOUT_STATUS, current.getCHECKOUT_STATUS());

                                                    editor.putString(CommonString.KEY_EMP_ID, current.getEMP_ID());
                                                    editor.putString(CommonString.KEY_GEO_TAG, current.getGEO_TAG());
                                                    editor.putString(CommonString.KEY_KEYACCOUNT_ID, current.getKEYACCOUNT_ID());
                                                    editor.putString(CommonString.KEY_STORETYPE_ID, current.getSTORETYPE_ID());
                                                    editor.putString(CommonString.KEY_CLASS_ID, current.getCLASS_ID());

                                                    editor.putString(CommonString.KEY_POG_TYPE_ID, current.getPOG_TYPE_ID());
                                                    editor.putString(CommonString.KEY_UPLOAD_STATUS, current.getUPLOAD_STATUS());
                                                    editor.commit();

                                                    if (!coverageObj.getStatus().equalsIgnoreCase("N")) {
                                                        //if(db.isFilledAdhoc(store_id, visit_date)){
                                                        Intent in = new Intent(StoreListActivity.this, StoreWisePerformanceActivity.class);
                                                        startActivity(in);
                                                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                                    } else {
                                                        new UploadTask(StoreListActivity.this, store_id).execute();
                                                    }
                                                } else {
                                                    String msg = getString(R.string.you_need_to_be_in_the_store) + "\n " + getString(R.string.distance_from_the_store) + " - " + distance + " " + getString(R.string.meters);
                                                    //dialog.cancel();
                                                    AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
                                                    builder.setTitle(getResources().getString(R.string.dialog_title));
                                                    builder.setMessage(msg).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                                                        public void onClick(DialogInterface dialog1, int id) {

                                                            dialog1.cancel();
                                                        }
                                                    });

                                                    AlertDialog alert = builder.create();

                                                    alert.show();
                                                }

                                            } else {

                                                editor = preferences.edit();
                                                editor.putString(CommonString.KEY_STORE_FLAG, store_flag_str);
                                                editor.putString(CommonString.KEY_STORE_FLAG_FACING_HIDE, current.getFACING_HIDE());
                                                editor.putString(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                                                editor.putString(CommonString.KEY_STORE_NAME, current.getSTORE_NAME());
                                                editor.putString(CommonString.KEY_VISIT_DATE, current.getVISIT_DATE());
                                                editor.putString(CommonString.KEY_CAMERA_ALLOW, current.getCAMERA_ALLOW());
                                                editor.putString(CommonString.KEY_CHECKOUT_STATUS, current.getCHECKOUT_STATUS());
                                                editor.putString(CommonString.KEY_CLASS_ID, current.getCLASS_ID());
                                                editor.putString(CommonString.KEY_EMP_ID, current.getEMP_ID());
                                                editor.putString(CommonString.KEY_GEO_TAG, current.getGEO_TAG());
                                                editor.putString(CommonString.KEY_KEYACCOUNT_ID, current.getKEYACCOUNT_ID());
                                                editor.putString(CommonString.KEY_STORETYPE_ID, current.getSTORETYPE_ID());
                                                editor.putString(CommonString.KEY_POG_TYPE_ID, current.getPOG_TYPE_ID());
                                                editor.putString(CommonString.KEY_UPLOAD_STATUS, current.getUPLOAD_STATUS());
                                                editor.commit();
                                                new UploadTask(StoreListActivity.this, store_id).execute();
                                                //dialog.cancel();
                                            }

                                        } else {
                                            if (coverageObj.getStatus().equals("N")) {
                                                Intent in = new Intent(StoreListActivity.this, StoreimageActivity.class);
                                                in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                                                in.putExtra(CommonString.KEY_STORE_ID, store_id);
                                                in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                                                startActivity(in);
                                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                            } else {
                                                Snackbar.make(v, R.string.title_store_list_checkout_Already_filled, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                            }
                                        }
                                    }
                                }
                            } else {
                                Snackbar.make(v, R.string.title_store_list_checkout_Already_filled, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                            }
                        }
                    }
                }
            });

            viewHolder.imgview_navigation.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent in = new Intent(context, StoreRouteActivity.class);
                    in.putExtra(CommonString.KEY_STORE_LIST, current);
                    startActivity(in);
                }
            });

            viewHolder.cancel_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    cancelStore(current);
                }
            });

            viewHolder.chkbtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                   /* String visit_xml = "";
                    String onXML = "";
                    ArrayList<Visit_Type_Master_GetterSetter> visittypelist = db.getUploadedVisitType(store_id);

                    if (visittypelist.size() > 0) {
                        for (int j = 0; j < visittypelist.size(); j++) {
                           // Log.e("visit_type_id", String.valueOf(visittypelist.get(j).getVISIT_TYPE_ID()));
                            if(String.valueOf(visittypelist.get(j).getVISIT_TYPE_ID()).equalsIgnoreCase("[3]")){
                                onXML = "[VISIT_TYPE_STATUS]"
                                        + "[MID]" + 0 + "[/MID]"
                                        + "[USERID]" + userId + "[/USERID]"
                                        + "[STORE_ID]" + store_id + "[/STORE_ID]"
                                        + "[VISIT_TYPE_ID]" + "3" + "[/VISIT_TYPE_ID]"
                                        + "[/VISIT_TYPE_STATUS]";
                            }
                            else if(String.valueOf(visittypelist.get(j).getVISIT_TYPE_ID()).equalsIgnoreCase("[2]")){
                                onXML = "[VISIT_TYPE_STATUS]"
                                        + "[MID]" + 0 + "[/MID]"
                                        + "[USERID]" + userId + "[/USERID]"
                                        + "[STORE_ID]" + store_id + "[/STORE_ID]"
                                        + "[VISIT_TYPE_ID]" + "2" + "[/VISIT_TYPE_ID]"
                                        + "[/VISIT_TYPE_STATUS]";
                            }
                            else{
                                onXML = "[VISIT_TYPE_STATUS]"
                                        + "[MID]" + 0 + "[/MID]"
                                        + "[USERID]" + userId + "[/USERID]"
                                        + "[STORE_ID]" + store_id + "[/STORE_ID]"
                                        + "[VISIT_TYPE_ID]" +"1"+ "[/VISIT_TYPE_ID]"
                                        + "[/VISIT_TYPE_STATUS]";
                            }

                            visit_xml = visit_xml + onXML;
                        }
                        final String sos_xml = "[DATA]" + visit_xml + "[/DATA]";
                        Log.e("visit_xml_data", sos_xml);
                    }*/

                    AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
                    builder.setMessage(R.string.wantcheckout).setCancelable(false).setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {

                            boolean coaching_visit_flag = false;
                            //Enable disable According to Configuration
                            ArrayList<ConfigurationMasterGetterSetter> configurationData = db.getConfigurationMasterData(country_id);
                            if (configurationData.size() > 0) {

                                for (int i = 0; i < configurationData.size(); i++) {
                                    if (configurationData.get(i).getCONFIGURE().get(0).equalsIgnoreCase("COACHING VISIT") && configurationData.get(i).getACTIVE().get(0).equalsIgnoreCase("1")) {
                                        coaching_visit_flag = true;
                                        break;
                                    }
                                }
                            }
                            //}

                            //show Coaching visit
                            if (coaching_visit_flag) {
                                Intent intent = new Intent(StoreListActivity.this, CoachingVisitActivity.class);
                                intent.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                                intent.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                                startActivity(intent);
                                finish();
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            } else {
                                if (CheckNetAvailability()) {
                                    Intent i = new Intent(StoreListActivity.this, StoreCheckoutImageActivity.class);
                                    i.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                                    i.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                                    startActivity(i);
                                    overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                } else {
                                    Snackbar.make(recyclerView, R.string.nonetwork, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                                }
                            }
                        }
                    }).setNegativeButton(R.string.closed, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            dialog.cancel();
                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            });

        }

        public boolean CheckNetAvailability() {

            boolean connected = false;
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
                // we are connected to a network
                connected = true;
            }
            return connected;
        }

        @Override
        public int getItemCount() {
            return data.size();
        }

        class MyViewHolder extends RecyclerView.ViewHolder {

            TextView txt, address;
            ImageView icon;
            LinearLayout parent_layout;
            ImageView imageview;
            ImageView imgview_navigation;
            Button chkbtn, cancel_btn;
            CardView Cardbtn;

            public MyViewHolder(View itemView) {
                super(itemView);
                txt = (TextView) itemView.findViewById(R.id.storelistviewxml_storename);
                address = (TextView) itemView.findViewById(R.id.storelistviewxml_storeaddress);

                parent_layout = (LinearLayout) itemView.findViewById(R.id.storenamelistview_layout);
                //imageview = (ImageView) itemView.findViewById(R.id.imageView2);

                imageview = (ImageView) itemView.findViewById(R.id.storelistviewxml_storeico);
                imgview_navigation = (ImageView) itemView.findViewById(R.id.navigate);

                chkbtn = (Button) itemView.findViewById(R.id.chkout);
                cancel_btn = (Button) itemView.findViewById(R.id.btn_cancel);
                Cardbtn = (CardView) itemView.findViewById(R.id.card_view);

            }
        }

    }


    void showMyDialog(final String storeCd, final String storeName, final String status, final String visitDate, final String checkout_status, final String GeotagStatus, final StoreBean current) {
        dialog = new Dialog(this);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.dialogbox);
        final RadioGroup radioGroup = (RadioGroup) dialog.findViewById(R.id.radiogrpvisit);
        radioGroup.setOnCheckedChangeListener((group, checkedId) -> {
            // find which radio button is selected
            if (checkedId == R.id.yes) {
                if (GeotagStatus.equalsIgnoreCase("Y")) {
                    boolean flag = true;
                    //for test
                    //  boolean flag = false;
                    if (coverage.size() > 0) {
                        for (int i = 0; i < coverage.size(); i++) {
                            if (store_id.equals(coverage.get(i).getStoreId())) {
                                flag = false;
                                break;
                            }
                        }
                    }
                    boolean flag_entry = true;
                    int distance = 0;
                    //geo fencing enabled only if GEO_FENCING equals 1 for COUNTRY_ID
                    if (flag && geoFencingGetterSetters.size() > 0 && geoFencingGetterSetters.get(0).getGEO_FENCING().get(0).equals("1")) {
                        distanceGeoPhence = Integer.parseInt(geoFencingGetterSetters.get(0).getDISTANCE_MTR().get(0));
                        double store_lat = Double.parseDouble(current.getLATITUDE());
                        double store_lon = Double.parseDouble(current.getLONGITUDE());
                        if (store_lat != 0.0 && store_lon != 0.0) {
                            distance = distFrom(store_lat, store_lon, lat, lon);
                            if (distance > distanceGeoPhence) {
                                flag_entry = false;
                            } else {
                                String msg = getString(R.string.distance_from_the_store) + " " + distance + " meters";
                                Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
                            }
                        }
                    }
                    if (flag_entry) {
                        editor = preferences.edit();
                        editor.putString(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                        editor.putString(CommonString.KEY_STORE_FLAG_FACING_HIDE, current.getFACING_HIDE());
                        editor.putString(CommonString.KEY_STORE_NAME, current.getSTORE_NAME());
                        editor.putString(CommonString.KEY_VISIT_DATE, current.getVISIT_DATE());
                        editor.putString(CommonString.KEY_CAMERA_ALLOW, current.getCAMERA_ALLOW());
                        editor.putString(CommonString.KEY_CHECKOUT_STATUS, current.getCHECKOUT_STATUS());
                        editor.putString(CommonString.KEY_CLASS_ID, current.getCLASS_ID());
                        editor.putString(CommonString.KEY_EMP_ID, current.getEMP_ID());
                        editor.putString(CommonString.KEY_GEO_TAG, current.getGEO_TAG());
                        editor.putString(CommonString.KEY_KEYACCOUNT_ID, current.getKEYACCOUNT_ID());
                        editor.putString(CommonString.KEY_STORETYPE_ID, current.getSTORETYPE_ID());
                        editor.putString(CommonString.KEY_POG_TYPE_ID, current.getPOG_TYPE_ID());
                        editor.putString(CommonString.KEY_UPLOAD_STATUS, current.getUPLOAD_STATUS());
                        editor.putString(CommonString.KEY_STORE_FLAG, store_flag_str);
                        editor.commit();

                        if (flag == true) {
                            Intent in = new Intent(StoreListActivity.this, StoreimageActivity.class);
                            in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                            in.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                            in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            dialog.cancel();
                        } else {
                            if (store_flag_str.equals(CommonString.FROM_ADDITIONAL) || store_flag_str.equals(CommonString.FROM_ADDITIONAL_ADHOC)) {
                                dialog.cancel();
                                Snackbar.make(recyclerView, R.string.title_store_list_checkout_Already_filled, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                            } else if (store_flag_str.equals(CommonString.FROM_PHARMA)) {
                                Intent in = new Intent(StoreListActivity.this, PharmaActivity.class);
                                startActivity(in);
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                dialog.cancel();
                            } else {
                                Intent in = new Intent(StoreListActivity.this, StoreWisePerformanceActivity.class);
                                startActivity(in);
                                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                dialog.cancel();
                            }
                        }
                    } else {
                        String msg = getString(R.string.you_need_to_be_in_the_store) + "\n " + getString(R.string.distance_from_the_store) + " - " + distance + " " + getString(R.string.meters);
                        dialog.cancel();
                        AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
                        builder.setTitle(getResources().getString(R.string.dialog_title));
                        builder.setMessage(msg).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog1, int id) {

                                dialog1.cancel();
                            }
                        });

                        AlertDialog alert = builder.create();

                        alert.show();
                    }

                } else {
                    dialog.cancel();
                    AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
                    builder.setTitle(getResources().getString(R.string.dialog_title));
                    builder.setMessage(R.string.first_geotag_the_store).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id) -> {
                        editor = preferences.edit();
                        editor.putString(CommonString.KEY_STORE_FLAG_FACING_HIDE, current.getFACING_HIDE());
                        editor.putString(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                        editor.putString(CommonString.KEY_STORE_NAME, current.getSTORE_NAME());
                        editor.putString(CommonString.KEY_VISIT_DATE, current.getVISIT_DATE());
                        editor.putString(CommonString.KEY_CAMERA_ALLOW, current.getCAMERA_ALLOW());
                        editor.putString(CommonString.KEY_CHECKOUT_STATUS, current.getCHECKOUT_STATUS());
                        editor.putString(CommonString.KEY_CLASS_ID, current.getCLASS_ID());
                        editor.putString(CommonString.KEY_EMP_ID, current.getEMP_ID());
                        editor.putString(CommonString.KEY_GEO_TAG, current.getGEO_TAG());
                        editor.putString(CommonString.KEY_KEYACCOUNT_ID, current.getKEYACCOUNT_ID());
                        editor.putString(CommonString.KEY_STORETYPE_ID, current.getSTORETYPE_ID());
                        editor.putString(CommonString.KEY_POG_TYPE_ID, current.getPOG_TYPE_ID());
                        editor.putString(CommonString.KEY_UPLOAD_STATUS, current.getUPLOAD_STATUS());
                        editor.putString(CommonString.KEY_STORE_FLAG, store_flag_str);

                        editor.commit();

                        Intent in = new Intent(StoreListActivity.this, GeoTagActivity.class);
                        in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                        in.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                        in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                        startActivity(in);
                        overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                        dialog1.cancel();
                    });

                    AlertDialog alert = builder.create();

                    alert.show();

                }


            } else if (checkedId == R.id.no) {
                dialog.cancel();
                editor = preferences.edit();
                editor.putString(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                editor.putString(CommonString.KEY_STORE_FLAG_FACING_HIDE, current.getFACING_HIDE());
                editor.putString(CommonString.KEY_STORE_NAME, current.getSTORE_NAME());
                editor.putString(CommonString.KEY_VISIT_DATE, current.getVISIT_DATE());
                editor.putString(CommonString.KEY_CAMERA_ALLOW, current.getCAMERA_ALLOW());
                editor.putString(CommonString.KEY_CHECKOUT_STATUS, current.getCHECKOUT_STATUS());
                editor.putString(CommonString.KEY_CLASS_ID, current.getCLASS_ID());
                editor.putString(CommonString.KEY_EMP_ID, current.getEMP_ID());
                editor.putString(CommonString.KEY_GEO_TAG, current.getGEO_TAG());
                editor.putString(CommonString.KEY_KEYACCOUNT_ID, current.getKEYACCOUNT_ID());
                editor.putString(CommonString.KEY_STORETYPE_ID, current.getSTORETYPE_ID());
                editor.putString(CommonString.KEY_POG_TYPE_ID, current.getPOG_TYPE_ID());
                editor.putString(CommonString.KEY_UPLOAD_STATUS, current.getUPLOAD_STATUS());
                editor.putString(CommonString.KEY_STORE_FLAG, store_flag_str);
                editor.commit();
                db.open();
                coverage = db.getCoverageWithStoreID_Data(current.getSTORE_ID(), visitDate);
                if (coverage.size() > 0) {
                    if (coverage.get(0).getStatus().equals(CommonString.KEY_INVALID) || coverage.get(0).getStatus().equals(CommonString.KEY_VALID)) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
                        builder.setMessage(R.string.DELETE_ALERT_MESSAGE).setCancelable(false).setPositiveButton(getResources().getString(R.string.yes), (dialog, id) -> {
                            UpdateStore(current.getSTORE_ID());
                            Intent in = new Intent(StoreListActivity.this, NonWorkingReason.class);
                            in.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                            in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                            startActivity(in);
                        }).setNegativeButton(getResources().getString(R.string.no), (dialog, id) -> dialog.cancel());
                        AlertDialog alert = builder.create();
                        alert.show();
                    } else {
                        Intent in = new Intent(StoreListActivity.this, NonWorkingReason.class);
                        in.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                        in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                        startActivity(in);
                    }
                } else {
                    Intent in = new Intent(StoreListActivity.this, NonWorkingReason.class);
                    in.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                    in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                    startActivity(in);
                }
            }
        });

        dialog.show();
    }


    public boolean setCheckedMethod(String store_cd) {

        boolean result_flag = false;
        for (int i = 0; i < coverage.size(); i++) {
            if (store_cd.equals(coverage.get(i).getStoreId())) {
                if (coverage.get(i).getOutTime() != null) {
                    result_flag = true;
                    break;
                }
            }
        }

        return result_flag;
    }


    public void UpdateStore(String storeid) {
        try {
            db.open();
            db.deleteTableWithStoreID(storeid);
            db.updateStoreStatus(storeid, storelist.get(0).getVISIT_DATE(), "N");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    public boolean checkleavestatus(String store_cd) {
        if (coverage.size() > 0) {
            for (int i = 0; i < coverage.size(); i++) {
                if (store_cd.equals(coverage.get(i).getStoreId())) {
                    if (coverage.get(i).getStatus().equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE)) {
                        result_flag = true;
                        break;
                    }
                } else {

                    result_flag = false;

                }
            }
        }
        return result_flag;
    }

    void cancelStore(final StoreBean current) {

        CoverageBean coverageData = db.getCoverageSpecificData(date, current.getSTORE_ID());
        if (coverageData.getStatus().equals(CommonString.KEY_INVALID) || coverageData.getStatus().equals(CommonString.KEY_VALID)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(StoreListActivity.this);
            builder.setMessage(R.string.DELETE_ALERT_MESSAGE).setCancelable(false).setPositiveButton(getResources().getString(R.string.yes), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {

                    UpdateStore(current.getSTORE_ID());

                    if (store_flag_str.equals(CommonString.FROM_JCP)) {
                        storelist = db.getStoreData(date, CommonString.KEY_JOURNEY_PLAN);
                    } else {
                        storelist = db.getStoreData(date, CommonString.KEY_ADHOC_JOURNEY_PLAN);
                    }

                    coverage = db.getCoverageData(date, store_flag_str);
                    adapter.notifyDataSetChanged();

                }
            }).setNegativeButton(getResources().getString(R.string.no), new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {


                    dialog.cancel();
                }
            });
            AlertDialog alert = builder.create();

            alert.show();
        }
    }

    boolean checkotherCheckedIn(String store_flag_str) {

        boolean flag_checked_in = false;
        ArrayList<CoverageBean> other_coverage_list;

        if (store_flag_str.equals(CommonString.FROM_JCP)) {

            if (isCheckedInFromStoreFlag(CommonString.FROM_DEVIATION)) {
                from_checkedIn = getString(R.string.adhoc);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_ADDITIONAL)) {
                from_checkedIn = getString(R.string.additional_stores);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_PHARMA)) {
                from_checkedIn = getString(R.string.pharma_stores);
                return true;
            }
        } else if (store_flag_str.equals(CommonString.FROM_ADDITIONAL)) {

            if (isCheckedInFromStoreFlag(CommonString.FROM_JCP)) {
                from_checkedIn = getString(R.string.jcp);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_DEVIATION)) {
                from_checkedIn = getString(R.string.adhoc);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_PHARMA)) {
                from_checkedIn = getString(R.string.pharma_stores);
                return true;
            }
        } else if (store_flag_str.equals(CommonString.FROM_PHARMA)) {

            if (isCheckedInFromStoreFlag(CommonString.FROM_JCP)) {
                from_checkedIn = getString(R.string.jcp);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_DEVIATION)) {
                from_checkedIn = getString(R.string.adhoc);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_ADDITIONAL)) {
                from_checkedIn = getString(R.string.additional_stores);
                return true;
            }
        } else {
            if (isCheckedInFromStoreFlag(CommonString.FROM_JCP)) {
                from_checkedIn = getString(R.string.jcp);
                return true;
            } else if (isCheckedInFromStoreFlag(CommonString.FROM_ADDITIONAL)) {
                from_checkedIn = getString(R.string.additional_stores);
                return true;
            }
        }

        return flag_checked_in;
    }

    boolean isCheckedInFromStoreFlag(String flagFromStore) {
        boolean flag = false;

        ArrayList<CoverageBean> other_coverage_list;

        other_coverage_list = db.getCoverageData(date, flagFromStore);

        for (int i = 0; i < other_coverage_list.size(); i++) {
            if (other_coverage_list.get(i).getStatus().equalsIgnoreCase(CommonString.KEY_INVALID) || other_coverage_list.get(i).getStatus().equalsIgnoreCase(CommonString.KEY_VALID)) {
                flag = true;
                break;
            }
        }

        return flag;
    }

    class Data {
        int value;
        String name;
    }

    private class UploadTask extends AsyncTask<Void, Data, String> {
        private Context context;
        String storeId;

        UploadTask(Context context, String storeId) {
            this.context = context;
            this.storeId = storeId;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new Dialog(context);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
            dialog.setContentView(R.layout.custom_dialog_progress);
            pb = (ProgressBar) dialog.findViewById(R.id.progressBar1);
            pb.getProgressDrawable().setColorFilter(getResources().getColor(R.color.colorPrimaryDark), android.graphics.PorterDuff.Mode.SRC_IN);
            percentage = (TextView) dialog.findViewById(R.id.percentage);
            message = (TextView) dialog.findViewById(R.id.message);
            dialog.setCancelable(false);
            dialog.show();
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {

                boolean no_jcp_flag = false;

                String resultHttp = "";
                data = new Data();

                data.value = 10;
                data.name = "JCP " + getResources().getString(R.string.download_data);
                publishProgress(data);

                XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
                factory.setNamespaceAware(true);
                XmlPullParser xpp = factory.newPullParser();

                // MAPPING_STOCK_ADHOC
                SoapObject request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_STOCK_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                HttpTransportSE androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                Object result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mappingStockGetterSetter = XMLHandlers.mappingStockXMLHandler(xpp, eventType);

                    String stocktable = mappingStockGetterSetter.getTable_MAPPING_STOCK();
                    if (stocktable != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setMappingStock(stocktable);

                    }

                    if (mappingStockGetterSetter.getSKU_ID().size() > 0) {
                        data.value = 45;
                        data.name = "MAPPING_STOCK_ADHOC " + getResources().getString(R.string.download_data);
                    } else {
                        // return "MAPPING_STOCK";
                    }

                }
                publishProgress(data);

                // MAPPING_T2P_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_T2P_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mappingt2PGetterSetter = XMLHandlers.mappingT2pXMLHandler(xpp, eventType);

                    String t2ptable = mappingt2PGetterSetter.getTable_MAPPING_T2P();
                    if (t2ptable != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setMappingT2p(t2ptable);

                    }

                    if (mappingt2PGetterSetter.getSTORE_ID().size() > 0) {
                        data.value = 50;
                        data.name = "MAPPING_T2P_ADHOC " + getResources().getString(R.string.download_data);

                    } else {
                        //return "MAPPING_T2P";
                    }

                }
                publishProgress(data);


                // MAPPING_PROMOTION_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_PROMOTION_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mappingPromotionGetterSetter = XMLHandlers.mappingPromotionXMLHandler(xpp, eventType);

                    String mapping_promotion_table = mappingPromotionGetterSetter.getTable_MAPPING_PROMOTION();
                    if (mapping_promotion_table != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setMappingPromotion(mapping_promotion_table);
                    }

                    if (mappingPromotionGetterSetter.getSTORE_ID().size() > 0) {
                        data.value = 75;
                        data.name = "MAPPING_PROMOTION_ADHOC " + getResources().getString(R.string.download_data);
                    }
                }
                publishProgress(data);

                //Gagan start code

                // MAPPING_ADDITIONAL_PROMOTION_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_ADDITIONAL_PROMOTION_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mapping_additional_promotion_masterGetterSetter = XMLHandlers.mappingAdditionalPromotionXMLHandler(xpp, eventType);

                    //if (mapping_additional_promotion_masterGetterSetter.getSTORE_ID().size() > 0) {
                    String mapping_additional_promotion_table = mapping_additional_promotion_masterGetterSetter.getTable_MAPPING_ADDITIONAL_PROMOTION();
                    if (mapping_additional_promotion_table != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        TableBean.setMappingAdditionalPromotion(mapping_additional_promotion_table);
                    }

                    if (mapping_additional_promotion_masterGetterSetter.getSTORE_ID().size() > 0) {
                        data.value = 80;
                        data.name = "MAPPING_ADDITIONAL_PROMOTION_ADHOC " + getResources().getString(R.string.download_data);
                    }
                }
                publishProgress(data);

                //STORE_PERFORMANCE_NEW_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "STORE_PERFORMANCE_NEW_ADHOC_REVISED");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    store_performance_masterGetterSetter = XMLHandlers.STORE_PERFORMANCEXMLHandler(xpp, eventType);

                    String table_store_performace = store_performance_masterGetterSetter.getTable_STORE_PERFORMANCE();
                    if (table_store_performace != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setStorePerformance(table_store_performace);
                    }

                    if (store_performance_masterGetterSetter.getSTORE_ID().size() > 0) {
                        data.value = 85;
                        data.name = "STORE_PERFORMANCE_NEW_ADHOC Data Download";
                    } else {
                        //return "STORE_PERFORMANCE";
                    }

                }
                publishProgress(data);


                //MAPPING_PLANOGRAM_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_PLANOGRAM_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mapping_planogram_masterGetterSetter = XMLHandlers.MAPPING_PLANOGRAM_XMLHandler(xpp, eventType);

                    String table_mapping_planogram = mapping_planogram_masterGetterSetter.getTable_MAPPING_PLANOGRAM();
                    if (table_mapping_planogram != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setMappingPlanogram(table_mapping_planogram);

                    }
                    if (mapping_planogram_masterGetterSetter.getKEYACCOUNT_ID().size() > 0) {
                        data.value = 92;
                        data.name = "MAPPING_PLANOGRAM Data Download";
                    } else {
                        //return "MAPPING_PLANOGRAM";
                    }
                }
                publishProgress(data);


                // MAPPING_SOS_TARGET_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "MAPPING_SOS_TARGET_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    mapping_sos_target_masterGetterSetter = XMLHandlers.MAPPING_SOS_TARGETXMLHandler(xpp, eventType);

                    //if (mapping_additional_promotion_masterGetterSetter.getSTORE_ID().size() > 0) {
                    String table_mapping_sos_target = mapping_sos_target_masterGetterSetter.getTable_MAPPING_SOS_TARGET();
                    if (table_mapping_sos_target != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setMappingSosTarget(table_mapping_sos_target);
                    }

                    if (mapping_sos_target_masterGetterSetter.getSTORE_ID().size() > 0) {
                        data.value = 95;
                        data.name = "MAPPING_SOS_TARGET_ADHOC " + getResources().getString(R.string.download_data);
                    }
                }
                publishProgress(data);


                //NO_CAMERA_LAST_VISIT_DATA_ADHOC
                request = new SoapObject(CommonString.NAMESPACE, CommonString.METHOD_NAME_UNIVERSAL_DOWNLOAD);
                request.addProperty("UserName", storeId);
                request.addProperty("Type", "NO_CAMERA_LAST_VISIT_DATA_ADHOC");
                request.addProperty("cultureid", culture_id);

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

                androidHttpTransport = new HttpTransportSE(CommonString.URL);
                androidHttpTransport.call(CommonString.SOAP_ACTION_UNIVERSAL, envelope);

                result = envelope.getResponse();

                if (result.toString() != null) {
                    xpp.setInput(new StringReader(result.toString()));
                    xpp.next();
                    eventType = xpp.getEventType();
                    noCameraLastVisitGetterSetter = XMLHandlers.noCameraLastVisitXMLHandler(xpp, eventType);

                    String table_no_camera = noCameraLastVisitGetterSetter.getTable_NO_CAMERA_LAST_VISIT_DATA();
                    if (table_no_camera != null) {
                        resultHttp = CommonString.KEY_SUCCESS;
                        //TableBean.setTable_NO_CAMERA_LAST_VISIT_DATA(table_no_camera);
                    }

                    if (noCameraLastVisitGetterSetter.getSKUGROUP_ID().size() > 0) {
                        data.value = 97;
                        data.name = "NO CAMERA LAST VISIT DATA" + getResources().getString(R.string.download_data);
                    }
                }
                publishProgress(data);


                //Images DownLoads

                //MAPPING_PLANOGRAM Image save into folder
                if (mapping_planogram_masterGetterSetter != null) {

                    for (int i = 0; i < mapping_planogram_masterGetterSetter.getIMAGE_PATH().size(); i++) {
                        //publishing image download

                        if (data.value < 100) {
                            data.value = data.value + 1;
                            publishProgress(data);
                        }

                        String image_name = mapping_planogram_masterGetterSetter.getPLANOGRAM_IMAGE().get(i);
                        String path = mapping_planogram_masterGetterSetter.getIMAGE_PATH().get(i);

                        String PATH = CommonString.getDownloadedImageFolder(context);
                        File file = new File(PATH);
                        if (!file.isDirectory()) {
                            file.mkdir();
                        }

                        if (!new File(PATH + image_name).exists()) {
                            if (!image_name.equalsIgnoreCase("NA") && !image_name.equalsIgnoreCase("")) {
                                URL url = new URL(path + "/" + image_name);
                                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                                c.setRequestMethod("GET");
                                c.getResponseCode();
                                c.connect();

                                if (c.getResponseCode() == 200) {
                                    int length = c.getContentLength();

                                    String size = new DecimalFormat("##.##").format((double) length / 1024) + " KB";

                                    //String PATH = Environment.getExternalStorageDirectory() + "/Download/GT_GSK_Images/";

                                    //  Environment.getExternalStorageDirectory() + "/GT_GSK_Images/" + _pathforcheck1;
                                    if (!size.equalsIgnoreCase("0 KB")) {
                                        File outputFile = new File(file, image_name);
                                        FileOutputStream fos = new FileOutputStream(outputFile);
                                        InputStream is1 = c.getInputStream();

                                        int bytes = 0;
                                        byte[] buffer = new byte[1024];
                                        int len1 = 0;

                                        while ((len1 = is1.read(buffer)) != -1) {
                                            bytes = (bytes + len1);
                                            // data.value = (int) ((double) (((double)
                                            // bytes) / length) * 100);
                                            fos.write(buffer, 0, len1);
                                        }
                                        fos.close();
                                        is1.close();
                                    }
                                }
                            }
                        }
                    }
                }

                //Gagan end code

                //Display Master Image save into folder
                if (displayMasterGetterSetter != null) {

                    for (int i = 0; i < displayMasterGetterSetter.getIMAGE_URL().size(); i++) {
                        //publishing image download

                        if (data.value < 100) {
                            data.value = data.value + 1;
                            publishProgress(data);
                        }

                        String image_name = displayMasterGetterSetter.getIMAGE_URL().get(i);
                        String img_url = displayMasterGetterSetter.getIMAGE_PATH().get(i);

                        String PATH = CommonString.getDownloadedImageFolder(context);
                        File file = new File(PATH);
                        if (!file.isDirectory()) {
                            file.mkdir();
                        }

                        if (!new File(PATH + image_name).exists()) {
                            if (!img_url.equalsIgnoreCase("") && !image_name.equalsIgnoreCase("")) {
                                URL url = new URL(img_url + image_name);
                                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                                c.setRequestMethod("GET");
                                c.getResponseCode();
                                c.connect();

                                if (c.getResponseCode() == 200) {
                                    int length = c.getContentLength();

                                    String size = new DecimalFormat("##.##").format((double) length / 1024) + " KB";

                                    //String PATH = Environment.getExternalStorageDirectory() + "/Download/GT_GSK_Images/";


                                    //  Environment.getExternalStorageDirectory() + "/GT_GSK_Images/" + _pathforcheck1;
                                    if (!size.equalsIgnoreCase("0 KB")) {
                                        File outputFile = new File(file, image_name);
                                        FileOutputStream fos = new FileOutputStream(outputFile);
                                        InputStream is1 = c.getInputStream();

                                        int bytes = 0;
                                        byte[] buffer = new byte[1024];
                                        int len1 = 0;

                                        while ((len1 = is1.read(buffer)) != -1) {
                                            bytes = (bytes + len1);
                                            // data.value = (int) ((double) (((double)
                                            // bytes) / length) * 100);
                                            fos.write(buffer, 0, len1);
                                        }
                                        fos.close();
                                        is1.close();
                                    }
                                }
                            }
                        }


                    }
                }


                //MAPPING_PLANOGRAM_STORE_WISE Image save into folder
                if (mappingPlanogramStorewiseGetterSetter != null) {

                    for (int i = 0; i < mappingPlanogramStorewiseGetterSetter.getIMAGE_PATH().size(); i++) {
                        //publishing image download

                        if (data.value < 100) {
                            data.value = data.value + 1;
                            publishProgress(data);
                        }

                        String image_name = mappingPlanogramStorewiseGetterSetter.getPLANOGRAM_IMAGE().get(i);
                        String path = mappingPlanogramStorewiseGetterSetter.getIMAGE_PATH().get(i);

                        String PATH = CommonString.getDownloadedImageFolder(context);
                        File file = new File(PATH);
                        if (!file.isDirectory()) {
                            file.mkdir();
                        }

                        if (!new File(PATH + image_name).exists()) {
                            if (!image_name.equalsIgnoreCase("NA") && !image_name.equalsIgnoreCase("")) {
                                URL url = new URL(path + "/" + image_name);
                                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                                c.setRequestMethod("GET");
                                c.getResponseCode();
                                c.connect();

                                if (c.getResponseCode() == 200) {
                                    int length = c.getContentLength();

                                    String size = new DecimalFormat("##.##").format((double) length / 1024) + " KB";

                                    //String PATH = Environment.getExternalStorageDirectory() + "/Download/GT_GSK_Images/";

                                    //  Environment.getExternalStorageDirectory() + "/GT_GSK_Images/" + _pathforcheck1;
                                    if (!size.equalsIgnoreCase("0 KB")) {
                                        File outputFile = new File(file, image_name);
                                        FileOutputStream fos = new FileOutputStream(outputFile);
                                        InputStream is1 = c.getInputStream();

                                        int bytes = 0;
                                        byte[] buffer = new byte[1024];
                                        int len1 = 0;

                                        while ((len1 = is1.read(buffer)) != -1) {
                                            bytes = (bytes + len1);
                                            // data.value = (int) ((double) (((double)
                                            // bytes) / length) * 100);
                                            fos.write(buffer, 0, len1);
                                        }
                                        fos.close();
                                        is1.close();
                                    }
                                }
                            }
                        }
                    }
                }

                db.open();
                db.createTable(mappingStockGetterSetter.getTable_MAPPING_STOCK());
                db.createTable(mappingt2PGetterSetter.getTable_MAPPING_T2P());
                db.createTable(mappingPromotionGetterSetter.getTable_MAPPING_PROMOTION());
                db.createTable(mapping_additional_promotion_masterGetterSetter.getTable_MAPPING_ADDITIONAL_PROMOTION());
                db.createTable(mapping_planogram_masterGetterSetter.getTable_MAPPING_PLANOGRAM());
                db.createTable(mapping_sos_target_masterGetterSetter.getTable_MAPPING_SOS_TARGET());
                db.createTable(noCameraLastVisitGetterSetter.getTable_NO_CAMERA_LAST_VISIT_DATA());
                db.createTable(store_performance_masterGetterSetter.getTable_STORE_PERFORMANCE());

                db.InsertAdhocFilled(storeId, visit_date);
                db.InsertMAPPING_T2P(mappingt2PGetterSetter, CommonString.TABLE_MAPPING_T2P_ADHOC);
                db.InsertMappingStock(mappingStockGetterSetter, CommonString.TABLE_MAPPING_STOCK_ADHOC);
                db.InsertMAPPING_PROMOTION(mappingPromotionGetterSetter, CommonString.TABLE_MAPPING_PROMOTION_ADHOC);
                db.InsertMAPPING_ADDITIONAL_PROMOTION(mapping_additional_promotion_masterGetterSetter, CommonString.TABLE_MAPPING_ADDITIONAL_PROMOTION_ADHOC);
                db.InsertSTORE_PERFORMANCE(store_performance_masterGetterSetter, CommonString.TABLE_STORE_PERFORMANCE_NEW_ADHOC);
                db.InsertMAPPING_PLANOGRAM(mapping_planogram_masterGetterSetter, CommonString.TABLE_MAPPING_PLANOGRAM_ADHOC);
                db.InsertMAPPING_SOS_TARGET(mapping_sos_target_masterGetterSetter, CommonString.TABLE_MAPPING_SOS_TARGET_ADHOC);
                db.InsertNO_CAMERA_LAST_VISIT_DATA(noCameraLastVisitGetterSetter, CommonString.TABLE_NO_CAMERA_LAST_VISIT_DATA_ADHOC);
            } catch (MalformedURLException e) {
                ResultFlag = false;
                str = CommonString.MESSAGE_EXCEPTION;
                return CommonString.MESSAGE_EXCEPTION;
            } catch (SocketTimeoutException e) {
                ResultFlag = false;
                str = CommonString.MESSAGE_SOCKETEXCEPTION;
                return CommonString.MESSAGE_SOCKETEXCEPTION;
            } catch (InterruptedIOException e) {

                ResultFlag = false;
                str = CommonString.MESSAGE_EXCEPTION;
                return CommonString.MESSAGE_EXCEPTION;

            } catch (IOException e) {

                ResultFlag = false;
                str = CommonString.MESSAGE_SOCKETEXCEPTION;
                return CommonString.MESSAGE_SOCKETEXCEPTION;
            } catch (XmlPullParserException e) {
                ResultFlag = false;
                str = CommonString.MESSAGE_XmlPull;
                return CommonString.MESSAGE_XmlPull;
            } catch (Exception e) {
                //Crashlytics.log(7, CommonString.MESSAGE_EXCEPTION, e.toString());
                // Crashlytics.logException(e.getCause());
                //Crashlytics.logException(new Exception(e.getCause()));
                ResultFlag = false;
                str = CommonString.MESSAGE_EXCEPTION;

                return CommonString.MESSAGE_EXCEPTION;
            }

            if (ResultFlag) {
                return "";
            } else {
                return str;
            }
        }

        @Override
        protected void onProgressUpdate(Data... values) {
            // TODO Auto-generated method stub

            pb.setProgress(values[0].value);
            percentage.setText(values[0].value + "%");
            message.setText(values[0].name);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if (s.equalsIgnoreCase("")) {
                dialog.dismiss();
                showAlert(getString(R.string.data_downloaded_successfully), true);
            } else {
                dialog.dismiss();
                showAlert(getString(R.string.datanotfound) + " " + s, false);
            }
        }
    }

    public void showAlert(String str, final boolean flag) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Parinaam");
        builder.setMessage(str).setCancelable(false).setPositiveButton(R.string.ok, (dialog, id) -> {
            if (flag) {
                if (storeCurrentObj != null) {
                    if (storeCurrentObj.getGEO_TAG().equalsIgnoreCase("N")) {
                        //If store is not geotagged
                        AlertDialog.Builder builder1 = new AlertDialog.Builder(StoreListActivity.this);
                        builder1.setTitle(getResources().getString(R.string.dialog_title));
                        builder1.setMessage(R.string.first_geotag_the_store).setCancelable(false).setPositiveButton(getResources().getString(R.string.ok), (dialog1, id1) -> {
                            Intent in = new Intent(StoreListActivity.this, GeoTagActivity.class);
                            in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                            in.putExtra(CommonString.KEY_STORE_ID, store_id);
                            in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            dialog1.cancel();
                        });
                        AlertDialog alert = builder1.create();
                        alert.show();
                    } else {
                        if (country_id.equals("2") && store_flag_str.equals(CommonString.FROM_DEVIATION)) {
                            Intent in = new Intent(StoreListActivity.this, VisitTypeStatusActivity.class);
                            in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                            in.putExtra(CommonString.KEY_STORE_ID, store_id);
                            in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            dialog.cancel();
                        } else {
                            Intent in = new Intent(StoreListActivity.this, StoreimageActivity.class);
                            in.putExtra(CommonString.KEY_STORE_FLAG, store_flag_str);
                            in.putExtra(CommonString.KEY_STORE_ID, store_id);
                            in.putExtra(CommonString.KEY_STORE_FLAG_FACING_HIDE, store_facing_hide);
                            startActivity(in);
                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                            dialog.cancel();
                        }
                    }
                }
            }
        });
        AlertDialog alert = builder.create();
        alert.show();
    }
}



