package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.adapter.SurveyQuestionAdapter;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.util.StorePreference;
import com.cygnusa.hyperm.util.TransparentProgressDialog;
import com.cygnusa.hyperm.util.UtilService;
import com.cygnusa.hyperm.wrappers.AnswerResponse;
import com.cygnusa.hyperm.wrappers.AssessmentQuestion;
import com.cygnusa.hyperm.wrappers.AssessmentQuestionResponse;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.HitCountModel;
import com.cygnusa.hyperm.wrappers.Survey;
import com.cygnusa.hyperm.wrappers.SurveyAnswer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


public class SurveyActivity extends AppCompatActivity {
    ApiService restService;
    TransparentProgressDialog progressDialog;
    TextView title;
    ListView surveyListView;

    public static Survey ASSESSMENT = new Survey();
    public static String TRAINING_ID = "";

    ArrayList<AssessmentQuestion> ASSESSMENT_QUESTIONS = new ArrayList<>();
    Button submitButton;
    String START_TIME = "";
    String END_TIME = "";
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    boolean isReview = false;
    SurveyQuestionAdapter adapter;

    String fromTime, toTime, finalTime;
    Calendar c;
    SimpleDateFormat df;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_survey);
        setupWindowAnimations();
        setupUI(findViewById(R.id.bgLayout));
        restService = ((MainApplication) getApplication()).getClient();
        title = findViewById(R.id.title);
        submitButton = findViewById(R.id.submitButton);
        isReview = ASSESSMENT.getStatus().trim().equalsIgnoreCase("3");
        surveyListView = findViewById(R.id.surveyListView);

        if (isReview) {
            submitButton.setVisibility(View.GONE);
            ((FrameLayout) submitButton.getParent()).setVisibility(View.GONE);
        } else {
            ((FrameLayout) submitButton.getParent()).setVisibility(View.VISIBLE);
            submitButton.setVisibility(View.VISIBLE);
        }

        title.setText(ASSESSMENT.getAssessmentname());
        title.setSelected(true);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(R.mipmap.back);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        getSupportActionBar().setTitle("");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
        @SuppressLint("PrivateResource")
        Drawable backArrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_material);
        backArrow.setColorFilter(getResources().getColor(R.color.btn_bg_color), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(backArrow);

        getCurrentTime();

        surveyListView.post(new Runnable() {
            @Override
            public void run() {
                if (isReview) {
                    getSurveyReview();
                } else {
                    getSurveyQuestion();
                }
            }
        });

        submitButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getToTime();
                onSubmitAnswer();
            }
        });
    }

    private void getCurrentTime() {
        c = Calendar.getInstance();
        System.out.println("fromTime " + c.getTime());

        df = new SimpleDateFormat("HH:mm:ss");
        fromTime = df.format(c.getTime());
        Log.e("fromTime", fromTime);
    }


    private void confirmClose() {
        new AlertDialog.Builder(SurveyActivity.this)
                .setMessage("Are you sure you want to exit?")
                .setPositiveButton("Yes",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(
                                    DialogInterface dialog,
                                    int which) {
                                getToTime();
                                finish();
                                SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                        R.anim.animation_f_leave);
                            }
                        }).setNegativeButton("No", null).show();
    }

    private void getToTime() {

        c = Calendar.getInstance();
        System.out.println("toTime " + c.getTime());

        df = new SimpleDateFormat("HH:mm:ss");
        toTime = df.format(c.getTime());
        Log.e("toTime", toTime);

        finalTime = UtilService.getTimeInterval(this, df, fromTime, toTime);

        if (StorePreference.getInstance(this).getBooleanValue(GlobalData.ISDSELOGIN))
            sendHitCountToServer();

    }


    private void sendHitCountToServer() {
        restService.sendAllHitCount(buildConfigData()).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    Log.e("responeHit", response.body().getMessage());
                } else {
                    Log.e("responeHit", response.body().getMessage());
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("responeHit", t.getMessage());
                }
            }
        });
    }

    private HitCountModel buildConfigData() {
        HitCountModel hitCountModel = new HitCountModel();
        hitCountModel.setPage("Feedback");
//        hitCountModel.setAssettopicid(Integer.valueOf(ASSESSMENT.getAssessmentid()));
//        hitCountModel.setCateid(Integer.parseInt(ASSESSMENT.getAssettypeid()));
        hitCountModel.setViewtime("0");
        return hitCountModel;
    }


    private void onSubmitAnswer() {
        if (ASSESSMENT_QUESTIONS != null && ASSESSMENT_QUESTIONS.size() > 0) {
            ArrayList<SurveyAnswer> answers = new ArrayList<>();
            END_TIME = format.format(new Date());
            for (AssessmentQuestion question : ASSESSMENT_QUESTIONS) {
                SurveyAnswer answer = new SurveyAnswer();
                answer.setAqid(question.getAqid());
                answer.setQid(question.getQid());
                if (question.getIs_mandatory().trim().equalsIgnoreCase("1")) {
                    if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("5")) {
                        if (!question.isSurveyOptionAnswered()) {
                            GlobalData.showToast(SurveyActivity.this, "Please answer all mandatory questions", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("6")) {
                        if (!question.isSurveyOptionAnswered()) {
                            GlobalData.showToast(SurveyActivity.this, "Please answer all mandatory questions", Toast.LENGTH_SHORT).show();
                            return;
                        }
                    } else if (!question.isSurveyAnswered()) {
                        GlobalData.showToast(SurveyActivity.this, "Please answer all mandatory questions", Toast.LENGTH_SHORT).show();
                        return;
                    }

                    if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("3")) {
                        answer.setSurvey_rating(question.getSurveyAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("4")) {
                        answer.setSurvey_text(question.getSurveyAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("5")) {
                        answer.setOptions(question.getSurveyOptionAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("6")) {
                        answer.setOptions(question.getSurveyOptionAnswer());
                    }
                } else {
                    if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("3")) {
                        answer.setSurvey_rating(question.getSurveyAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("4")) {
                        answer.setSurvey_text(question.getSurveyAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("5")) {
                        answer.setOptions(question.getSurveyOptionAnswer());
                    } else if (question.getQuestiontypeid() != null && question.getQuestiontypeid().trim().equalsIgnoreCase("6")) {
                        answer.setOptions(question.getSurveyOptionAnswer());
                    }
                }
                answers.add(answer);
            }

            Gson gson = new Gson();
            JsonElement jsonElement = gson.toJsonTree(
                    answers, new TypeToken<ArrayList<SurveyAnswer>>() {
                    }.getType());

            HashMap<String, String> map = new HashMap<>();
            map.put("ans_arr", jsonElement.toString());
            map.put("startdatetime", START_TIME);
            map.put("enddatetime", END_TIME);

            if (new UtilService().isNetworkAvailable(SurveyActivity.this)) {

                progressDialog = new TransparentProgressDialog(SurveyActivity.this);
                progressDialog.show();

                restService.postSurvey(ASSESSMENT.getAssessmentid(), map).enqueue(new Callback<AnswerResponse>() {
                    @Override
                    public void onResponse(Call<AnswerResponse> call, Response<AnswerResponse> response) {

                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }

                        if (response.body() != null && response.body().getStatus() == 200) {
                            GlobalData.showToast(SurveyActivity.this, "Feedback submitted successfully", Toast.LENGTH_SHORT).show();
                            finish();
                            SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                    R.anim.animation_f_leave);
                        } else if (response.body() != null && response.body().getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                            SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                    R.anim.animation_f_leave);
                        } else if (response.body() != null) {
                            GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                        } else if (response.errorBody() != null) {
                            Gson gson = new Gson();
                            ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                            GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                            if (message.getStatus() == 401) {
                                GlobalData.canLogout = true;
                                finish();
                                SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                                        R.anim.animation_f_leave);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<AnswerResponse> call, Throwable t) {
                        if (progressDialog != null && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                    }
                });
            } else {
                GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
            }

        }
    }

    private void setupWindowAnimations() {
        this.overridePendingTransition(R.anim.animation_enter,
                R.anim.animation_leave);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void onBackPressed() {
        if (isReview) {
            getToTime();
            finish();
            SurveyActivity.this.overridePendingTransition(R.anim.animation_f_enter,
                    R.anim.animation_f_leave);
        } else {
            confirmClose();
        }

    }

    @SuppressLint("StaticFieldLeak")
    private void getSurveyQuestion() {
        if (new UtilService().isNetworkAvailable(SurveyActivity.this)) {
            progressDialog = new TransparentProgressDialog(SurveyActivity.this);
            progressDialog.show();

            restService.getSurveyQuistion(ASSESSMENT.getAssessmentid()).enqueue(new Callback<AssessmentQuestionResponse>() {
                @Override
                public void onResponse(Call<AssessmentQuestionResponse> call, Response<AssessmentQuestionResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    if (response.body() != null && response.body().getStatus() == 200) {
                        ASSESSMENT_QUESTIONS = response.body().getData();
                        setSurveyQuestion();
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Call<AssessmentQuestionResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    @SuppressLint("StaticFieldLeak")
    private void getSurveyReview() {
        if (new UtilService().isNetworkAvailable(SurveyActivity.this)) {
            progressDialog = new TransparentProgressDialog(SurveyActivity.this);
            progressDialog.show();

            restService.getSurveyReviewQuistion(ASSESSMENT.getResult_id()).enqueue(new Callback<AssessmentQuestionResponse>() {
                @Override
                public void onResponse(Call<AssessmentQuestionResponse> call, Response<AssessmentQuestionResponse> response) {

                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }

                    if (response.body() != null && response.body().getStatus() == 200) {
                        ASSESSMENT_QUESTIONS = response.body().getData();
                        setSurveyQuestion();
                    } else if (response.body() != null && response.body().getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    } else if (response.body() != null) {
                        GlobalData.showToast(getBaseContext(), response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    } else if (response.errorBody() != null) {
                        Gson gson = new Gson();
                        ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                        GlobalData.showToast(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                        if (message.getStatus() == 401) {
                            GlobalData.canLogout = true;
                            finish();
                        }
                    }
                }

                @Override
                public void onFailure(Call<AssessmentQuestionResponse> call, Throwable t) {
                    if (progressDialog != null && progressDialog.isShowing()) {
                        progressDialog.dismiss();
                    }
                    GlobalData.showToast(getBaseContext(), "Connection Failure, try again!", Toast.LENGTH_SHORT).show();
                }
            });
        } else {
            GlobalData.showToast(getBaseContext(), "Please check your internet connection", Toast.LENGTH_SHORT).show();
        }
    }

    private void setSurveyQuestion() {
        adapter = new SurveyQuestionAdapter(SurveyActivity.this, ASSESSMENT_QUESTIONS, isReview);
        surveyListView.setAdapter(adapter);

        START_TIME = format.format(new Date());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (GlobalData.canLogout) {
            finish();
        }
    }

    public void setupUI(View view) {
        try {
            if (!(view instanceof EditText)) {
                view.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    public boolean onTouch(View v, MotionEvent event) {
                        hideSoftKeyboard(SurveyActivity.this);
                        return false;
                    }
                });
            }

            if (view instanceof ViewGroup) {
                for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                    View innerView = ((ViewGroup) view).getChildAt(i);
                    setupUI(innerView);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager inputMethodManager =
                    (InputMethodManager) activity.getSystemService(
                            Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(
                    activity.getCurrentFocus().getWindowToken(), 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}