package com.symbol.elearningapp;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;

import com.symbol.elearningapp.Utils.AppPreference;
import com.symbol.elearningapp.Utils.Constant;
import com.symbol.elearningapp.service.ClassDetail;
import com.symbol.elearningapp.service.RetrofitClient;
import com.symbol.elearningapp.service.ServiceApi;
import com.symbol.elearningapp.service.StudentDetails;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

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

public class ClassEditActivity extends AppCompatActivity {
    AppPreference appPreference;
    Calendar myCalendar;
    EditText etSubject, etDate, etTime;
    Button btnDel, btnEdit,btnAdd;
    int selectedIndex;
    ServiceApi serviceApi;
    ProgressDialog progress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_class_edit);
        appPreference = new AppPreference(this);
        serviceApi = RetrofitClient.getApiClient(Constant.baseUrl.BASE_URL).create(ServiceApi.class);
        etDate = findViewById(R.id.etdate1);
        etSubject = findViewById(R.id.etsubject1);
        etTime = findViewById(R.id.etclasstime1);
        btnDel = findViewById(R.id.btn_Delete);
        btnEdit = findViewById(R.id.btn_edit);
        btnAdd = findViewById(R.id.btn_add);
        selectedIndex = CommonData.getSelectedIndex();

        etDate.setText(CommonData.getClassDetails().get(selectedIndex).getDate());
        etSubject.setText(CommonData.getClassDetails().get(selectedIndex).getSubject());
        etTime.setText(CommonData.getClassDetails().get(selectedIndex).getClassTime());

        btnEdit.setOnClickListener(view -> {
            updateClassdetails();
        });
        btnDel.setOnClickListener(view -> {
            deleteClassdetails();
        });
        btnAdd.setOnClickListener(v -> {
            getStudentList();
        });
        myCalendar = Calendar.getInstance();
        DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear,
                                  int dayOfMonth) {

                myCalendar.set(Calendar.YEAR, year);
                myCalendar.set(Calendar.MONTH, monthOfYear);
                myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
                updateLabel();
            }

        };
        etDate.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                new DatePickerDialog(ClassEditActivity.this, date, myCalendar
                        .get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
                        myCalendar.get(Calendar.DAY_OF_MONTH)).show();
            }
        });
        etTime.setOnClickListener(new View.OnClickListener() {
            final Calendar c = Calendar.getInstance();
            int  mHour = c.get(Calendar.HOUR_OF_DAY);
            int  mMinute = c.get(Calendar.MINUTE);
            @Override
            public void onClick(View v) {
                TimePickerDialog timePickerDialog = new TimePickerDialog(ClassEditActivity.this,
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {

                                etTime.setText(hourOfDay + ":" + String.format("%02d", minute));
                            }
                        }, mHour, mMinute, true);
                timePickerDialog.show();
            }

        });
    }

    private void updateLabel() {
        String myFormat = "MM/dd/yy";
        SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);

        etDate.setText(sdf.format(myCalendar.getTime()));
    }

    public void deleteClassdetails() {
        progress = new ProgressDialog(this);
        progress.setTitle("Please wait");
        progress.setCancelable(false);
        progress.show();
        Call<String> userCall = serviceApi.deleteUser(CommonData.getClassDetails().get(CommonData.getSelectedIndex()).getId());
        userCall.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.code()==200) {
                    progress.dismiss();
                    appPreference.showToast("deleted Sucessfully");
                    stopActivity();
                } else {
                    appPreference.showToast("Server Error occured!!");
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                appPreference.showToast(t.getMessage());
            }

        });
    }

    public void getStudentList() {
        progress = new ProgressDialog(this);
        progress.setTitle("Please wait");
        progress.setCancelable(false);
        progress.show();
        Call<List<StudentDetails>> userCall = serviceApi.getStudents("class/students");
        userCall.enqueue(new Callback<List<StudentDetails>>() {
            @Override
            public void onResponse(Call<List<StudentDetails>> call, Response<List<StudentDetails>> response) {

                if (response.body()!=null)
                {
                    CommonData.setStudentDetailsList(response.body());
                    CommonData.setStudentDetailsHashMap(new HashMap<>());
                    CommonData.setStudentDetailsHashMap(new HashMap<>());
                    for(StudentDetails details : CommonData.getStudentDetailsList()){
                        CommonData.getStudentDetailsHashMap().put(details.getStudentName(),details);
                    }

                    progress.dismiss();
                    Intent intent = new Intent(ClassEditActivity.this, StudentListActivity.class);
                    intent.putExtra("key", "edit");
                    startActivity(intent);
                }
                else
                {
                    appPreference.showToast("Server Error occured!!");
                }
            }

            @Override
            public void onFailure(Call<List<StudentDetails>> call, Throwable t) {
                appPreference.showToast(t.getMessage());
                progress.dismiss();
            }

        });
    }

    public void updateClassdetails() {
        progress = new ProgressDialog(this);
        progress.setTitle("Please wait");
        progress.setCancelable(false);
        progress.show();
        String Subject = etSubject.getText().toString();
        String Date = etDate.getText().toString();
        String time = etTime.getText().toString();
        List<StudentDetails> listStudentDetails = new ArrayList<>();
        if (CommonData.getSelectedStudentDetailsHashMap()!= null) {
            for(Map.Entry<String, StudentDetails> entry : CommonData.getSelectedStudentDetailsHashMap().entrySet()) {
                StudentDetails value = entry.getValue();
                listStudentDetails.add(value);
            }
        }
        if (TextUtils.isEmpty(Subject)) {
            appPreference.showToast("Subject name is required.");
        } else if (TextUtils.isEmpty(Date)) {
            appPreference.showToast("Please select the date");
        } else if (TextUtils.isEmpty(time)) {
            appPreference.showToast("Please select the time");
        } else {
            Call<String> userCall = serviceApi.updateUser(new ClassDetail(CommonData.getClassDetails().get(CommonData.getSelectedIndex()).getId(), Subject, Date, time, listStudentDetails));
            userCall.enqueue(new Callback<String>() {
                @Override
                public void onResponse(Call<String> call, Response<String> response) {

                    if (response.body().equals("ok")) {
                        progress.dismiss();
                        appPreference.showToast("updated Sucessfully");
                        stopActivity();
                    } else {
                        appPreference.showToast("Server Error occured!!");
                    }
                }

                @Override
                public void onFailure(Call<String> call, Throwable t) {
                    appPreference.showToast(t.getMessage());
                }

            });
        }

    }
    private void stopActivity(){
        this.finish();
    }
}