package cpm.com.gskmtorange.dailyentry;

import android.Manifest;
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.location.Location;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
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.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

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.LocationListener;
import com.google.android.gms.location.LocationRequest;
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.maps.model.LatLng;

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.GetterSetter.CoverageBean;
import cpm.com.gskmtorange.GetterSetter.GeotaggingBeans;
import cpm.com.gskmtorange.GetterSetter.StoreBean;
import cpm.com.gskmtorange.R;
import cpm.com.gskmtorange.constant.CommonFunctions;
import cpm.com.gskmtorange.constant.CommonString;
import cpm.com.gskmtorange.download.DownloadActivity;
import cpm.com.gskmtorange.gsk_dailyentry.StoreWisePerformanceActivity;
import cpm.com.gskmtorange.storeinmap.StoreListMapActivity;
import cpm.com.gskmtorange.storeinmap.StoreListRouteActivity;
import cpm.com.gskmtorange.storeinmap.StoreRouteActivity;
import cpm.com.gskmtorange.xmlGetterSetter.ConfigurationMasterGetterSetter;
import cpm.com.gskmtorange.xmlGetterSetter.GeoFencingGetterSetter;

/**
 * Created by ashishc on 29-12-2016.
 */

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;
    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;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.storelistfablayout);
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        preferences = PreferenceManager.getDefaultSharedPreferences(this);

        context = this;

        CommonFunctions.updateLangResources(getApplicationContext(), 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, "");
        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(getApplicationContext(), DownloadActivity.class);
                startActivity(in);

                finish();
            }
        });

        if (Build.VERSION.SDK_INT >= 23 && ContextCompat.checkSelfPermission(getApplicationContext(),
                android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ContextCompat.checkSelfPermission(getApplicationContext(),
                        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();
        }

    }

    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(getApplicationContext(), 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);
                // Toast.makeText(getApplicationContext(), "startLocation - Lat" + lat + "Long" + lon, Toast.LENGTH_LONG).show();
            }
        }

    }

    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) {
        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();
                //  Toast.makeText(getApplicationContext(), "onconnected lat-" + lat + " Long-" + lon, Toast.LENGTH_SHORT).show();
            }
            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();

        CommonFunctions.updateLangResources(getApplicationContext(), preferences.getString(CommonString.KEY_LANGUAGE, ""));
        //toolbar.setTitle(getString(R.string.title_activity_store_list));
        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 {
            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());
            adapter = new StoreListActivity.ValueAdapter(getApplicationContext(), 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.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(getApplicationContext(), StoreListMapActivity.class);
            Intent in = new Intent(getApplicationContext(), StoreListRouteActivity.class);
            in.putExtra(CommonString.KEY_STORE_LIST, storelist);
            startActivity(in);
        }

        return super.onOptionsItemSelected(item);
    }


    public 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;

        }

        @Override
        public StoreListActivity.ValueAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int i) {

            View view = inflator.inflate(R.layout.storelist_child, parent, false);

            StoreListActivity.ValueAdapter.MyViewHolder holder = new StoreListActivity.ValueAdapter.MyViewHolder(view);

            return holder;
        }

        @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.txt);

            viewHolder.txt.setText(current.getSTORE_NAME());
            viewHolder.address.setText(current.getADDRESS());

           /* if (current.getCHECKOUT_STATUS().equalsIgnoreCase(CommonString.KEY_VALID)) {
                viewHolder.chkbtn.setVisibility(View.VISIBLE);
                viewHolder.imageview.setVisibility(View.INVISIBLE);
            } else*/
            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_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);
                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);
                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);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                viewHolder.cancel_btn.setVisibility(View.GONE);
                viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));

            }/* else if (checkleavestatus(storeid)) {
                viewHolder.imageview.setVisibility(View.VISIBLE);
                viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation);
                viewHolder.chkbtn.setVisibility(View.INVISIBLE);
            }*/
            /*else if (current.getCHECKOUT_STATUS().equalsIgnoreCase(CommonString.KEY_INVALID)) {

            }*/
           /* else if (coverage.size() > 0) {
                String statusleave = "";

                for (int i = 0; i < coverage.size(); i++) {

                    if (storeid.equals(coverage.get(i).getStoreId())) {
                        statusleave = coverage.get(i).getStatus();


                        if (statusleave.equalsIgnoreCase(CommonString.STORE_STATUS_LEAVE)) {

                            viewHolder.imageview.setVisibility(View.VISIBLE);
                            viewHolder.imageview.setBackgroundResource(R.mipmap.exclamation);
                            viewHolder.chkbtn.setVisibility(View.INVISIBLE);


                        } else if (coverage.get(i).getStatus().equalsIgnoreCase(CommonString.KEY_VALID)) {
                            viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
                            viewHolder.chkbtn.setVisibility(View.VISIBLE);
                            viewHolder.imageview.setVisibility(View.INVISIBLE);

                        } else if (coverage.get(i).getStatus().equalsIgnoreCase(CommonString.KEY_INVALID)) {

                            viewHolder.imageview.setVisibility(View.INVISIBLE);
                            viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                            viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.green));
                        } else {

                            viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.colorOrange));
                            viewHolder.imageview.setVisibility(View.INVISIBLE);
                            viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                        }

                        break;


                    }

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

                            if (coverage.get(i).getOutTime() == null) {

                                if (storeid.equals(coverage.get(i).getStoreId())) {
                                    viewHolder.imageview.setVisibility(View.VISIBLE);
                                    //  viewHolder.imageview.setBackgroundResource(R.mipmap.checkin);
                                    viewHolder.chkbtn.setVisibility(View.INVISIBLE);
                                    viewHolder.Cardbtn.setCardBackgroundColor(getResources().getColor(R.color.green));


                                }
                                break;
                            }

                        }*//*

                }

            }*/ 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);
            }


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

                    store_id = current.getSTORE_ID();

                    if (current.getUPLOAD_STATUS().equalsIgnoreCase(CommonString.KEY_U)) {
                        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


                        // showMyDialog(store_id, current.getSTORE_NAME(), "Yes", current.getVISIT_DATE(), current.getCHECKOUT_STATUS());

                        if(checkotherCheckedIn(store_flag_str)){
                            String from;
                            if (store_flag_str.equals(CommonString.FROM_JCP)) {
                                from = getString(R.string.adhoc);
                            }else {
                                from = getString(R.string.jcp);
                            }
                            Snackbar.make(v, getString(R.string.title_store_list_checkout_current) + " - " + from, Snackbar.LENGTH_SHORT).setAction("Action", null).show();
                        }
                        else {
                            if (!setcheckedmenthod(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_JCP)){
                                        showMyDialog(store_id, current.getSTORE_NAME(), "Yes", current.getVISIT_DATE(), current.getCHECKOUT_STATUS(), current.getGEO_TAG(), current);
                                    }
                                    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);
                                            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(getApplicationContext(), 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) {

                    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;
                                            }
                                        }
                                    }

                                    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, CheckoutActivity.class);
                                        i.putExtra(CommonString.KEY_STORE_ID, current.getSTORE_ID());
                                        startActivity(i);*/

                                            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);

        RadioGroup radioGroup = (RadioGroup) dialog.findViewById(R.id.radiogrpvisit);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // find which radio button is selected
                if (checkedId == R.id.yes) {

                    if (!GeotagStatus.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 (/*true*/distance > distanceGeoPhence) {
                                    flag_entry = false;
                                }
                                else {
                                    String msg = getString(R.string.distance_from_the_store) + " " + distance + " meters";

                                    Toast.makeText(getApplicationContext(), 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_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();


                            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());
                                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),
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog1,
                                                                int id) {

                                                dialog1.cancel();
                                            }
                                        });

                        AlertDialog alert = builder.create();

                        alert.show();

                    }


                } else if (checkedId == R.id.no) {

                    dialog.cancel();

                    GSKOrangeDB db = new GSKOrangeDB(StoreListActivity.this);
                    db.open();

                    coverage = db.getCoverageWithStoreID_Data(current.getSTORE_ID());

                    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),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog,
                                                                    int 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, CommonString.FROM_JCP);
                                                    startActivity(in);

                                                }
                                            })
                                    .setNegativeButton(getResources().getString(R.string.no),
                                            new DialogInterface.OnClickListener() {
                                                public void onClick(DialogInterface dialog,
                                                                    int 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, CommonString.FROM_JCP);
                            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, CommonString.FROM_JCP);
                        startActivity(in);
                    }

                }
            }

        });


        dialog.show();
    }


    public boolean setcheckedmenthod(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) {

        db.open();
        db.deleteTableWithStoreID(storeid);

        db.updateStoreStatus(storeid, storelist.get(0).getVISIT_DATE(), "N");

    }


    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) {
        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),
                            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)){
            other_coverage_list = db.getCoverageData(date,CommonString.FROM_DEVIATION );
        }
        else {

            other_coverage_list = db.getCoverageData(date,CommonString.FROM_JCP );
        }

        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_checked_in = true;
                break;
            }
        }

        return flag_checked_in;
    }
}



