package com.cpm.lorealbaautomation.timer;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.widget.Toolbar;

import android.widget.Toast;

import com.google.gson.Gson;
import com.cpm.lorealbaautomation.Database.Lorealba_Database;
import com.cpm.lorealbaautomation.DealarBoardActivity;
import com.cpm.lorealbaautomation.R;
import com.cpm.lorealbaautomation.constant.AlertandMessages;
import com.cpm.lorealbaautomation.constant.CommonFunctions;
import com.cpm.lorealbaautomation.constant.CommonString;
import com.cpm.lorealbaautomation.delegates.PrefHelper;
import com.cpm.lorealbaautomation.gsonGetterSetter.JCPGetterSetter;
import com.cpm.lorealbaautomation.retrofit.PostApi;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;


public class TimerActivity extends AppCompatActivity {
    String process_data_Status = "", visit_date, username, counter_id;
    SharedPreferences preferences = null;
    SharedPreferences.Editor editor = null;
    Lorealba_Database db;
    Context context;

    Timer timer;
    TimerTask timerTask;
    //we are going to use a handler to be able to run in our TimerTask
    final Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_timer);
        context = this;
        db = new Lorealba_Database(context);
        db.open();
        calculate_ids();
        //calling method first time......
        call_timer();
        checkwait_status(context);
    }


    public void startTimer() {
        try {
            //set a new Timer
            timer = new Timer();
            //initialize the TimerTask's job
            initializeTimerTask();
            //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms
            // 4 minuts 240,000
            timer.schedule(timerTask, 20000, 240000);
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void stoptimertask() {
        //stop the timer, if it's not already null
        try {
            if (timer != null) {
                timer.cancel();
                timer = null;
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public void initializeTimerTask() {
        timerTask = new TimerTask() {
            public void run() {
                //use a handler to run a toast that shows the current timestamp
                handler.post(() -> {
                    //get the current timeStamp
                    int duration = Toast.LENGTH_SHORT;
                    if (CommonFunctions.checkNetIsAvailable(context)) {
                        checkwait_status(context);
                    } else {
                        call_timer();
                        AlertandMessages.showToastMsg(context, getString(R.string.nonetwork));
                    }
                    //show the toast
                    Toast toast = Toast.makeText(context, "Checking Server Status", duration);
                    toast.show();
                });
            }
        };
    }

    private void call_timer() {
        startTimer();
    }


    private void calculate_ids() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        if (!CommonFunctions.isTablet(context)) {
            toolbar.setTitleTextAppearance(context, R.style.changestext_sizefor_mobile);
        }
        GifImageView gifImageView = (GifImageView) findViewById(R.id.GifImageView);
        gifImageView.setGifImageResource(R.drawable.sliding_square_loader_view);
       preferences = PrefHelper.getPrefs(context);
        counter_id = preferences.getString(CommonString.KEY_COUNTER_ID, "");
        visit_date = preferences.getString(CommonString.KEY_DATE, "");
        username = preferences.getString(CommonString.KEY_USERNAME, "");
        setTitle("Processing Data - " + username);
    }

    private void checkwait_status(Context context) {
        db.open();
        if (db.isCheck_Old_Product(visit_date)) {
            check_data_managing_status(context, CommonString.Key_Download_Status);
        }
    }


    private void check_data_managing_status(final Context context, String service_name) {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("Downloadtype", service_name);
            jsonObject.put("Username", "");
            jsonObject.put("Param1", counter_id);
            jsonObject.put("Param2", "");
            String jsonString = jsonObject.toString();

            try {

                OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).writeTimeout(CommonString.TIMEOUT,
                        TimeUnit.SECONDS).connectTimeout(CommonString.TIMEOUT, TimeUnit.SECONDS).build();
                RequestBody jsonData = RequestBody.create(MediaType.parse("application/json"), jsonString);
                Retrofit adapter = new Retrofit.Builder().baseUrl(CommonString.URL).client(okHttpClient).addConverterFactory(GsonConverterFactory.create()).build();
                PostApi api = adapter.create(PostApi.class);
                Call<ResponseBody> call = api.getTabjournePlan(jsonData);
                call.enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                        ResponseBody responseBody = response.body();
                        String data = null;
                        if (responseBody != null && response.isSuccessful()) {
                            try {
                                assert response.body() != null;
                                data = response.body().string();
                                data = data.substring(1, data.length() - 1).replace("\\", "");
                                if (data.equalsIgnoreCase(CommonString.KEY_FAILURE)) {
                                    process_data_Status = "";
                                    AlertandMessages.showToastMsg((Activity) context, CommonString.KEY_FAILURE + " Please try again ");

                                } else if (!data.contains("No Data")) {
                                    JCPGetterSetter jcpObject = new Gson().fromJson(data, JCPGetterSetter.class);
                                    if (jcpObject != null && jcpObject.getDownloadStatus() != null) {
                                        process_data_Status = jcpObject.getDownloadStatus().get(0).getDownloadStatus().trim();
                                        if (process_data_Status.equalsIgnoreCase("Wait")) {
                                        } else {
                                            ///finsh
                                            stoptimertask();
                                            startActivity(new Intent(context, DealarBoardActivity.class));
                                            overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                                            TimerActivity.this.finish();
                                        }
                                    }
                                } else {
                                    process_data_Status = "";
                                }

                            } catch (Exception e) {
                                process_data_Status = "";
                                e.fillInStackTrace();
                                AlertandMessages.showToastMsg((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")");
                            }
                        } else {
                            process_data_Status = "";
                            AlertandMessages.showToastMsg(context, CommonString.MESSAGE_NO_RESPONSE_SERVER);
                        }
                    }

                    @Override
                    public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                        process_data_Status = "";
                        AlertandMessages.showToastMsg((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION);
                    }
                });

            } catch (Exception e) {
                process_data_Status = "";
                e.fillInStackTrace();
                AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_SOCKETEXCEPTION + "(" + e.toString() + ")");
            }

        } catch (JSONException e) {
            process_data_Status = "";
            AlertandMessages.showAlertlogin((Activity) context, CommonString.MESSAGE_INVALID_JSON);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        db.open();
        if (db.isCheck_Old_Product(visit_date)) {
            if (process_data_Status != null && !process_data_Status.equals("") && process_data_Status.equalsIgnoreCase("Download")) {
                ///finsh
                startActivity(new Intent(context, DealarBoardActivity.class));
                overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                TimerActivity.this.finish();
            }
        }
    }


    @Override
    public void onBackPressed() {
//        super.onBackPressed();
    }
}
