package com.b2lmobitech.spottest.network;

import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.Snackbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NoConnectionError;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import com.b2lmobitech.spottest.R;
import com.b2lmobitech.spottest.utils.Preference;
import com.google.firebase.iid.FirebaseInstanceId;

import java.util.Map;

/**
 * Created by home on 3/24/2018.
 */

public class MyRequestQueue {
    private static Activity activity;
    private RequestQueue mRequestQueue;
    private static Window window;
    private static ConnectivityManager cm;
    private static CoordinatorLayout coordinatorLayout;
    private static Snackbar snackbar;
    private static ProgressBar progressBar;

    private MyRequestQueue(Activity activity){
        MyRequestQueue.activity = activity;
        progressBar=activity.findViewById(R.id.progressBar);
        coordinatorLayout=activity.findViewById(R.id.coordinatorLayout);
        mRequestQueue = getRequestQueue();
        window=activity.getWindow();
        cm = (ConnectivityManager) activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        if(coordinatorLayout!=null) {
            snackbar = Snackbar.make(coordinatorLayout, "sss", Snackbar.LENGTH_INDEFINITE);
            ViewGroup contentLay = (ViewGroup) snackbar.getView().findViewById(android.support.design.R.id.snackbar_text).getParent();
            ProgressBar item = new ProgressBar(activity);
            contentLay.addView(item);
        }

    }

    public static synchronized MyRequestQueue getInstance(Activity activity){
        return new MyRequestQueue(activity);
    }

    private RequestQueue getRequestQueue(){
        if(mRequestQueue == null){
            mRequestQueue = Volley.newRequestQueue(activity.getApplicationContext());
        }
        return mRequestQueue;
    }

    public void addToQueue(String URL, final Map<String, String> params,String message, final MyRequestFinishedListener myRequestFinishedListener){



        showProgressBar(message);
        Preference preference= Preference.getInstance(activity);
        StringRequest postRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                        hideProgressBar();
                        myRequestFinishedListener.requestResult(response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        hideProgressBar();
                        Log.d("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                params.put("deviceid", FirebaseInstanceId.getInstance().getId());
                return params;
            }
        };
        postRequest.setRetryPolicy(new DefaultRetryPolicy(240 * 1000, 1, 1.0f));
        mRequestQueue.add(postRequest);
    }

    public void addToQueue(String URL, final Map<String, String> params, final MyRequestFinishedListener myRequestFinishedListener){

        if(isNoNetwork()){
            return;
        }

        showProgressBar();
        StringRequest postRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                        hideProgressBar();
                        myRequestFinishedListener.requestResult(response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        hideProgressBar();
                        Log.d("Error.Response", error.toString());
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                return params;
            }
        };
        postRequest.setRetryPolicy(new DefaultRetryPolicy(240 * 1000, 1, 1.0f));
        mRequestQueue.add(postRequest);
    }

    public void addToQueueWithoutProgress(String URL, final Map<String, String> params, final MyRequestFinishedListener myRequestFinishedListener){

        StringRequest postRequest = new StringRequest(Request.Method.POST,URL,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response) {
                        // response
                        Log.d("Response", response);
                        myRequestFinishedListener.requestResult(response);
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        // error
                        hideProgressBar();
                        Log.d("Error.Response", error.toString());
                        //--swathi--

                        //--swathi--
                       // Toast.makeText(activity, "Myrequestqueue="+error.toString(),Toast.LENGTH_LONG).show();
                        //myRequestFinishedListener.requestResult(error.toString());
                       //--swathi
//                        String message = null;
//                        if (error instanceof NetworkError) {
//                            message = "Cannot connect to Internet...Please check your connection!";
//                        } else if (error instanceof ServerError) {
//                            message = "The server could not be found. Please try again after some time!!";
//                        } else if (error instanceof AuthFailureError) {
//                            message = "Cannot connect to Internet...Please check your connection!";
//                        } else if (error instanceof ParseError) {
//                            message = "Parsing error! Please try again after some time!!";
//                        } else if (error instanceof NoConnectionError) {
//                            message = "Cannot connect to Internet...Please check your connection!";
//                        } else if (error instanceof TimeoutError) {
//                            message = "Connection TimeOut! Please check your internet connection.";
//                        }
//                        myRequestFinishedListener.requestResult(message);
//                        //--swathi
//                        Log.d("message", message);
                    }
                }
        ) {
            @Override
            protected Map<String, String> getParams()
            {
                return params;
            }
        };

        postRequest.setRetryPolicy(new DefaultRetryPolicy(240 * 1000, 1, 1.0f));
        mRequestQueue.add(postRequest);
    }

    public void showProgressBar(String message){
        if(!message.isEmpty()){
            snackbar.setText(message);
            snackbar.show();
        }
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    public void showProgressBar(){
        progressBar.setVisibility(View.VISIBLE);
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    public void hideProgressBar(){
        if(snackbar!=null && snackbar.isShown()){
            snackbar.dismiss();
        }
        if(progressBar!=null){
            progressBar.setVisibility(View.GONE);
        }

        window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
    }

    public boolean isNoNetwork() {
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        if(networkInfo != null && networkInfo.isConnected()){
            return false;
        }else{
            Toast.makeText(activity.getApplicationContext(),"No Inernet Connection",Toast.LENGTH_SHORT).show();
            return true;
        }
    }

    public boolean isNoInternet() {
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return networkInfo == null || !networkInfo.isConnected();
    }

    public interface MyRequestFinishedListener {
        void requestResult(String response);
    }

}
