package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.cygnusa.hyperm.fragments.DSETrainerFeedback;
import com.cygnusa.hyperm.fragments.DSETrainingFeedback;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.wrappers.CommonResponse;
import com.cygnusa.hyperm.wrappers.DSEFeedBackAnswer;
import com.cygnusa.hyperm.wrappers.DSETrainingFeedbackData;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllDSETrainingFeedbackSummary;
import com.cygnusa.hyperm.wrappers.SurveyAnswer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Objects;

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

public class DSEViewFeedbackActivity extends AppCompatActivity {
    private TextView txtTrainingName, txtTrainingStartDate, txtTrainingDuration, txtTrainingEndDate, txtTrainingVenue,
            txtTrainingTotalPArticipant, smpin, participantName, dealerName;

    LinearLayout llout_remaining;
    private ImageView imgAttendance;
    private Button trainingFeedback, trainersFeedback, btnsubmit, btncancel;
    FragmentManager manager;
    private EditText edtRemarks;
    ApiService restService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_dse_feedback_view);

        initViews();
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        startActivity(new Intent(DSEViewFeedbackActivity.this, ClassRoomDSETainingActivity.class));
        finish();
        this.overridePendingTransition(R.anim.animation_f_enter,
                R.anim.animation_f_leave);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            startActivity(new Intent(DSEViewFeedbackActivity.this, ClassRoomDSETainingActivity.class));
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    private void initViews() {

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        toolbar.setContentInsetStartWithNavigation(0);
        toolbar.setTitle("");
        Objects.requireNonNull(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);
        restService = ((MainApplication) getApplication()).getClient();
        txtTrainingName = findViewById(R.id.txtTrainingName);
        txtTrainingStartDate = findViewById(R.id.txtTrainingStartDate);
        txtTrainingDuration = findViewById(R.id.txtTrainingDuration);
        txtTrainingEndDate = findViewById(R.id.txtTrainingEndDate);
        txtTrainingVenue = findViewById(R.id.txtTrainingVenue);
        txtTrainingTotalPArticipant = findViewById(R.id.txtTrainingTotalPArticipant);
        llout_remaining = findViewById(R.id.lloutWholeLayout);
        llout_remaining.setVisibility(View.GONE);
        TextView txtShowmore = findViewById(R.id.txtShowmore);
        imgAttendance = findViewById(R.id.imgAttendance);
        edtRemarks = findViewById(R.id.edtRemarks);

        trainersFeedback = findViewById(R.id.trainers_feedback);
        trainingFeedback = findViewById(R.id.training_feedback);
        manager = getSupportFragmentManager();

        btnsubmit = findViewById(R.id.btnsubmit);
        btncancel = findViewById(R.id.btncancel);


        btncancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        btnsubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (validate()) {
                    sendAllTrainingFeedbacktoServer();
                }
            }
        });

        GetAllDSETrainingDetails();


        trainersFeedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = manager.beginTransaction();
                trainingFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_black));
                trainersFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_white));
                transaction.replace(R.id.container, new DSETrainerFeedback());
                transaction.commit();
            }
        });

        trainingFeedback.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FragmentTransaction transaction = manager.beginTransaction();
                trainersFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_black));
                trainingFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_white));
                transaction.replace(R.id.container, new DSETrainingFeedback());
                transaction.commit();
            }
        });

        smpin = findViewById(R.id.smpin);
        participantName = findViewById(R.id.txtParticipantName);
        dealerName = findViewById(R.id.txtDealerName);
        txtTrainingVenue.setSelected(true);
        dealerName.setSelected(true);
        txtShowmore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (txtShowmore.getText().toString().equalsIgnoreCase("Show More")) {
                    txtShowmore.setText(getResources().getText(R.string.showless));
                    llout_remaining.setVisibility(View.VISIBLE);
                } else {
                    txtShowmore.setText(getResources().getText(R.string.showmore));
                    llout_remaining.setVisibility(View.GONE);
                }
            }
        });

        setAllData();
    }


    private void sendAllTrainingFeedbacktoServer() {

        HashMap<String, String> sendObj = new HashMap<>();

        sendObj.put("startdatetime", GlobalData.DSEFEEDBACKVIEW.getStartDate());
        sendObj.put("enddatetime", GlobalData.DSEFEEDBACKVIEW.getEndDate());
        sendObj.put("remarks", edtRemarks.getText().toString().trim());
        ArrayList<DSEFeedBackAnswer> answers = new ArrayList<>();
        DSEFeedBackAnswer answer = new DSEFeedBackAnswer();

        for (int i = 0; i < GlobalData.DSEFeedbackQuestions.getQuestions().size(); i++) {
            answer = new DSEFeedBackAnswer();
            answer.setAqid(GlobalData.DSEFeedbackQuestions.getQuestions().get(i).getAqid());
            answer.setQid(GlobalData.DSEFeedbackQuestions.getQuestions().get(i).getQid());
            ArrayList<String> strings = new ArrayList<>();
            strings.add(GlobalData.DSEFeedbackQuestions.getQuestions().get(i).getSelectedOption());
            answer.setOptions(strings);
            answers.add(answer);

        }

        Gson gson = new Gson();
        JsonElement jsonElement = gson.toJsonTree(
                answers, new TypeToken<ArrayList<SurveyAnswer>>() {
                }.getType());
        sendObj.put("ans_arr", jsonElement.toString());
        restService.dsePostSurvey(GlobalData.DSEFEEDBACKVIEW.getAssessmentid(), sendObj).enqueue(new Callback<CommonResponse>() {
            @Override
            public void onResponse(Call<CommonResponse> call, Response<CommonResponse> response) {
                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        GlobalData.toast(getApplicationContext(), response.body().getMessage());
                        startActivity(new Intent(DSEViewFeedbackActivity.this, ClassRoomDSETainingActivity.class));
                        finish();
                    } else {
                        GlobalData.toast(getApplicationContext(), response.body().getResponseText());
                    }
                } else if (response.body() != null && response.body().getStatus() == 401) {
                    GlobalData.canLogout = true;
                    finish();
                } else if (response.errorBody() != null) {
                    Gson gson = new Gson();
                    ErrorResponse message = gson.fromJson(response.errorBody().charStream(), ErrorResponse.class);
                    GlobalData.showToast(getApplicationContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    }
                }
            }

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

    private boolean validate() {

        if (edtRemarks.getText().toString().equalsIgnoreCase("")) {
            Toast.makeText(DSEViewFeedbackActivity.this, "Please Enter Remarks", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (edtRemarks.getText().toString().length() < 60) {
            Toast.makeText(DSEViewFeedbackActivity.this, "Please Enter Remarks min 60 letters", Toast.LENGTH_SHORT).show();
            return false;
        }

        if (GlobalData.DSEFeedbackQuestions.getQuestions() != null && GlobalData.DSEFeedbackQuestions.getQuestions().size() > 0) {
            for (int j = 0; j < GlobalData.DSEFeedbackQuestions.getQuestions().size(); j++) {
                if (GlobalData.DSEFeedbackQuestions.getQuestions().get(j).getSelectedOption() == null) {
                    Toast.makeText(DSEViewFeedbackActivity.this, "Please Choose mark for all questions", Toast.LENGTH_SHORT).show();
                    return false;
                }
            }
        }

        return true;
    }

    private void GetAllDSETrainingDetails() {

        restService.getDSETrainingFeedback(GlobalData.DSEFEEDBACKVIEW.getAssessmentid()).enqueue(new Callback<GetAllDSETrainingFeedbackSummary>() {
            @Override
            public void onResponse(Call<GetAllDSETrainingFeedbackSummary> call, Response<GetAllDSETrainingFeedbackSummary> response) {
                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        DSETrainingFeedbackData summaryData = response.body().getDseTrainingFeedbackData();
                        if (summaryData.getQuestions() != null && summaryData.getQuestions().size() > 0) {

                            GlobalData.DSEFeedbackQuestions = summaryData;

                            FragmentTransaction transaction = manager.beginTransaction();
                            trainersFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_black));
                            trainingFeedback.setBackground(getResources().getDrawable(R.drawable.border_login_white));
                            transaction.replace(R.id.container, new DSETrainingFeedback());
                            transaction.commit();

                        } else {
                            GlobalData.toast(getApplicationContext(), response.body().getMessage());

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

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

    private void setAllData() {

        if (GlobalData.DSEFEEDBACKVIEW != null) {
            txtTrainingName.setText(GlobalData.DSEFEEDBACKVIEW.getTitle());

            String endDate = GlobalData.DSEFEEDBACKVIEW.getEndDate();
            String startDate = GlobalData.DSEFEEDBACKVIEW.getStartDate();

            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String startDateString = "", endDateString = "";
            try {
                startDateString = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Objects.requireNonNull(format.parse(startDate)));
                endDateString = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault()).format(Objects.requireNonNull(format.parse(endDate)));
            } catch (ParseException e) {
                e.printStackTrace();
            }

            String endTime = GlobalData.DSEFEEDBACKVIEW.getEndDate();
            String startTime = GlobalData.DSEFEEDBACKVIEW.getStartDate();

            SimpleDateFormat timeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String startTimeString = "", endTimeString = "";
            Date date1, date2;
            long difference = 0;
            try {
                date1 = timeFormat.parse(startTime);
                date2 = timeFormat.parse(endTime);
                startTimeString = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(Objects.requireNonNull(timeFormat.parse(startTime)));
                endTimeString = new SimpleDateFormat("HH:mm", Locale.getDefault()).format(Objects.requireNonNull(timeFormat.parse(endTime)));
                difference = date1.getTime() - date2.getTime();
            } catch (ParseException e) {
                e.printStackTrace();
            }
            int days = (int) (difference / (1000 * 60 * 60 * 24));
            int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days)) / (1000 * 60 * 60));
            int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours)) / (1000 * 60);

            min = (hours < 0 ? -min : min);
            Log.i("======= min", " :: " + min);

            txtTrainingStartDate.setText(startDateString);
            txtTrainingEndDate.setText(endDateString);
            txtTrainingTotalPArticipant.setText(GlobalData.DSEFEEDBACKVIEW.getTotal_participants());
            txtTrainingDuration.setText(GlobalData.DSEFEEDBACKVIEW.getOrganizer_name());
            txtTrainingVenue.setText(GlobalData.DSEFEEDBACKVIEW.getVenueAddress());
            if (GlobalData.user.getData().getSmpin() != null)
                smpin.setText(GlobalData.user.getData().getSmpin());
            participantName.setText(GlobalData.DSEFEEDBACKVIEW.getTraining_id());
            dealerName.setText(GlobalData.user.getData().getDealer().getName());


            Glide.with(DSEViewFeedbackActivity.this).load(GlobalData.DSEFEEDBACKRESPONSEGROUPIMAGE)
                    .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.drawable.nodatafound)).into(imgAttendance);
        }
    }
}
