package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
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.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.cygnusa.hyperm.fragments.TrainingTrainerFeedback;
import com.cygnusa.hyperm.fragments.TrainingTrainingFeedback;
import com.cygnusa.hyperm.util.ApiService;
import com.cygnusa.hyperm.util.GlobalData;
import com.cygnusa.hyperm.util.MainApplication;
import com.cygnusa.hyperm.wrappers.ErrorResponse;
import com.cygnusa.hyperm.wrappers.GetAllTrainerTrainingFeedbackSummary;
import com.cygnusa.hyperm.wrappers.TrainerFeedBackData;

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

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

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

    LinearLayout llout_remaining, llout_buttonLayout;
    private ImageView imgAttendance;
    private Button trainingFeedback, trainersFeedback;
    FragmentManager manager;
    ApiService restService;
    TextView txtShowmore;

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

        setContentView(R.layout.activity_trainer_feedback_view);

        initViews();

    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        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) {
            finish();
            onBackPressed();
        }
        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);
        txtShowmore = findViewById(R.id.txtShowmore);
        imgAttendance = findViewById(R.id.imgAttendance);
        llout_buttonLayout = findViewById(R.id.llout_buttonLayout);
        llout_buttonLayout.setVisibility(View.GONE);

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

        GetAllTrainingTrainingDetails();


        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 TrainingTrainerFeedback());
                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 TrainingTrainingFeedback());
                transaction.commit();
            }
        });

        smpin = findViewById(R.id.smpin);
        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 GetAllTrainingTrainingDetails() {

        restService.getTrainingTrainingFeedback(GlobalData.DSEFEEDBACKVIEW.getAssessmentid()).enqueue(new Callback<GetAllTrainerTrainingFeedbackSummary>() {
            @Override
            public void onResponse(Call<GetAllTrainerTrainingFeedbackSummary> call, Response<GetAllTrainerTrainingFeedbackSummary> response) {
                if (response.body() != null) {
                    if (response.body().getResponse().equalsIgnoreCase("Success")) {
                        TrainerFeedBackData summaryData = response.body().getTrainerFeedBackDataList();
                        if (summaryData != null) {
                            GlobalData.TrainerFeedbackData = 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 TrainingTrainingFeedback());
                            transaction.commit();


                        } else {
                            GlobalData.toast(getApplicationContext(), "No data found.");
                            GlobalData.TrainerFeedbackData = null;
                            onBackPressed();
                        }
                    } else {
                        GlobalData.toast(getApplicationContext(), response.body().getMessage());
                        GlobalData.TrainerFeedbackData = null;
                        onBackPressed();
                    }
                } 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<GetAllTrainerTrainingFeedbackSummary> call, Throwable t) {
                if (t.getMessage() != null) {
                    Log.e("tmess", t.getMessage());
                }

                txtShowmore.setText(getResources().getText(R.string.showmore));
                llout_remaining.setVisibility(View.GONE);
            }
        });
    }

    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);
            txtTrainingDuration.setText(GlobalData.DSEFEEDBACKVIEW.getOrganizer_name());
            txtTrainingVenue.setText(GlobalData.DSEFEEDBACKVIEW.getVenueAddress());
            txtTrainingTotalPArticipant.setText(GlobalData.DSEFEEDBACKVIEW.getTotal_participants());
            smpin.setText(GlobalData.DSEFEEDBACKVIEW.getTraining_id());


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