package com.cygnusa.hyperm;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.Typeface;
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.core.widget.NestedScrollView;
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.AMAttendanceMarkingFragment;
import com.cygnusa.hyperm.fragments.TrainingScoreCommandFragment;
import com.cygnusa.hyperm.fragments.TrainingSummaryFragment;
import com.cygnusa.hyperm.pickimage.bean.PickResult;
import com.cygnusa.hyperm.pickimage.listeners.IPickResult;
import com.cygnusa.hyperm.qr_code.ScanCallback;
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.ErrorResponse;
import com.cygnusa.hyperm.wrappers.SingleAttendance;

import org.joda.time.LocalDate;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Objects;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.cygnusa.hyperm.fragments.AMAttendanceMarkingFragment.aDialog;
import static com.cygnusa.hyperm.fragments.AMAttendanceMarkingFragment.mPreviewView;
import static com.cygnusa.hyperm.util.GlobalData.scheduledDataList;
import static com.cygnusa.hyperm.util.GlobalData.singleDateOneList;

public class AMAttendanceActivity extends AppCompatActivity implements IPickResult {
    private TextView txtTrainingUID, txtTrainerName, txtSegment, txtTrainingName, txtTrainingStartDate, txtTrainingStartTime, txtTravelInformation,
            txtTrainingSubmissionDays, txtTrainingDuration, txtTrainingEndDate, txtTrainingEndTime, txtTrainingVenue,
            txtTrainingTotalPArticipant;
    private ImageView imgAttendance;
    String IMAGE_PATH = "";
    private Button btnAttendance, btnScore, summary;
    FragmentManager manager;
    private LinearLayout llout_remaining;
    private LinearLayout layoutDate;
    private String id1;
    private String id2;
    List<String> eTime = new ArrayList<>();
    List<String> sTime = new ArrayList<>();
    ApiService restService;

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

        setContentView(R.layout.activity_attendance_training_schedule);

        initViews();

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

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

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

        FragmentTransaction transaction = manager.beginTransaction();
        transaction.replace(R.id.container, new AMAttendanceMarkingFragment());
        transaction.commit();
    }

    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);

        layoutDate = findViewById(R.id.layoutDate);
        restService = ((MainApplication) getApplication()).getClient();

        @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);

        txtTrainingName = findViewById(R.id.txtTrainingName);
        txtTrainerName = findViewById(R.id.txtTrainerName);
        txtTrainingUID = findViewById(R.id.txtTrainingUID);
        txtSegment = findViewById(R.id.txtSegment);
        txtTrainingStartDate = findViewById(R.id.txtTrainingStartDate);
        txtTrainingStartTime = findViewById(R.id.txtTrainingStartTime);
        txtTravelInformation = findViewById(R.id.txtTravelInformation);
        txtTrainingSubmissionDays = findViewById(R.id.txtTrainingSubmissionDays);
        txtTrainingDuration = findViewById(R.id.txtTrainingDuration);
        txtTrainingEndDate = findViewById(R.id.txtTrainingEndDate);
        txtTrainingEndTime = findViewById(R.id.txtTrainingEndTime);
        txtTrainingVenue = findViewById(R.id.txtTrainingVenue);
        txtTrainingTotalPArticipant = findViewById(R.id.txtTrainingTotalPArticipant);
        btnScore = findViewById(R.id.score);
        llout_remaining = findViewById(R.id.llout_remaining);
        btnAttendance = findViewById(R.id.attendance);
        summary = findViewById(R.id.summary);
        llout_remaining.setVisibility(View.GONE);
        TextView txtShowmore = findViewById(R.id.txtShowmore);
        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);
                }
            }
        });
        manager = getSupportFragmentManager();


        NestedScrollView scrollView = (NestedScrollView) findViewById(R.id.scrollView);
        scrollView.setFillViewport(true);

        if (GlobalData.scheduledDataList != null && GlobalData.scheduledDataList.size() > 0) {
            txtTrainingName.setText(GlobalData.scheduledDataList.get(0).getTitle());
            txtTrainingUID.setText(scheduledDataList.get(0).getTraining_id());
            txtTrainerName.setText(scheduledDataList.get(0).getOrganizerName());

            txtSegment.setText(scheduledDataList.get(0).getSegmentName());

            String endDate = GlobalData.scheduledDataList.get(0).getEndDate();
            String startDate = GlobalData.scheduledDataList.get(0).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.scheduledDataList.get(0).getEndDate();
            String startTime = GlobalData.scheduledDataList.get(0).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);
            txtTrainingStartTime.setText(startTimeString);
            txtTrainingEndTime.setText(endTimeString);
            if (GlobalData.scheduledDataList.get(0).getScheduleName() != null && !GlobalData.scheduledDataList.get(0).getScheduleName().isEmpty())
                txtTravelInformation.setText(GlobalData.scheduledDataList.get(0).getScheduleName());
            else {
                txtTravelInformation.setText("N/A");
            }
            txtTrainingSubmissionDays.setText(String.valueOf(GlobalData.scheduledDataList.get(0).getTrainingDays()));
            txtTrainingDuration.setText(min + " Minutes");
            txtTrainingVenue.setText(GlobalData.scheduledDataList.get(0).getVenueAddress());
            if (GlobalData.scheduledDataList.get(0).getParticipant() != null && GlobalData.scheduledDataList.get(0).getParticipant().size() > 0) {
                txtTrainingTotalPArticipant.setText(String.valueOf(GlobalData.scheduledDataList.get(0).getParticipant().size()));
            }
        }

        String s = GlobalData.scheduledDataList.get(0).getStartdate();
        String e = GlobalData.scheduledDataList.get(0).getEnddate();

        LocalDate start = LocalDate.parse(s);
        LocalDate end = LocalDate.parse(e);
        List<LocalDate> totalDates = new ArrayList<>();
        while (!start.isAfter(end)) {
            totalDates.add(start);

            start = start.plusDays(1);
        }

        String startTime = GlobalData.scheduledDataList.get(0).getStarttime();
        String endTime = GlobalData.scheduledDataList.get(0).getEndtime();

        try {
            JSONArray arrayFromTime = new JSONArray(startTime);
            for (int i = 0; i < arrayFromTime.length(); i++) {
                id1 = (String) arrayFromTime.get(i);
                sTime.add(id1);
            }
            JSONArray arrayToTime = new JSONArray(endTime);
            for (int i = 0; i < arrayToTime.length(); i++) {
                id2 = (String) arrayToTime.get(i);
                eTime.add(id2);
            }
        } catch (JSONException e1) {
            sTime.add(startTime);
            eTime.add(endTime);
            e1.printStackTrace();
        }

        int trainingDays = Integer.parseInt(GlobalData.scheduledDataList.get(0).getTrainingDays());

        for (int i = 0; i < trainingDays; i++) {
            TextView txtDays = new TextView(this);
            txtDays.setTextSize(15);
            txtDays.setTextColor(Color.parseColor("#00344C"));
            txtDays.setPadding(0, 0, 0, 0);
            if (sTime.size() - 1 >= i && eTime.size() - 1 >= i)
                txtDays.setText("Day " + (i + 1) + " : " + totalDates.get(i) + " " + sTime.get(i) + " - " + eTime.get(i));
            txtDays.setTypeface(Typeface.DEFAULT_BOLD);
            layoutDate.addView(txtDays);
        }
        imgAttendance = findViewById(R.id.imgAttendance);
        if (scheduledDataList.get(0).getTrainingGroupImage() != null && !scheduledDataList.get(0).getTrainingGroupImage().equalsIgnoreCase("")) {


            Glide.with(AMAttendanceActivity.this).load(Objects.requireNonNull(getApplicationContext())).load(scheduledDataList.get(0).getTrainingGroupImage())
                    .thumbnail(Glide.with(AMAttendanceActivity.this).load(R.drawable.camera))
                    .apply(new RequestOptions().fitCenter().diskCacheStrategy(DiskCacheStrategy.ALL)
                            .placeholder(R.drawable.camera)).into(imgAttendance);
        }


        imgAttendance.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                PickImageDialog.build(new PickSetup().setButtonOrientation(LinearLayout.HORIZONTAL)).setOnPickCancel(new IPickCancel() {
//                    @Override
//                    public void onCancelClick() {
//
//                    }
//                }).show(AMAttendanceActivity.this);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == 2276) {
            IMAGE_PATH = data.getStringExtra("IMAGE_PATH");
            if (GlobalData.IMAGECLICKPOS == -1) {
                Glide.with(this).load(new File(IMAGE_PATH))
                        .thumbnail(Glide.with(this).load(R.drawable.gif_loader))
                        .into(imgAttendance);
                sendImageToServer(IMAGE_PATH);
            } else {

                setUploadPhoto(GlobalData.IMAGECLICKPOS, IMAGE_PATH);

                AMAttendanceMarkingFragment.isUpdates();
            }

        } else if (resultCode == RESULT_CANCELED && requestCode == 2276) {
            IMAGE_PATH = "";
        }
    }

    private void sendImageToServer(String IMAGE_PATH) {
        File file = new File(IMAGE_PATH);
        RequestBody reqFile = RequestBody.create(MediaType.parse("image/*"), file);
        MultipartBody.Part body = MultipartBody.Part.createFormData("file", file.getAbsolutePath(), reqFile);
        RequestBody requestEmail =
                RequestBody.create(
                        MediaType.parse("multipart/form-data"), singleDateOneList.getScheduleId());
        restService.postGroupCheckImage(requestEmail, body).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(AMAttendanceActivity.this, "Upload successfully");
                    } else {
                        GlobalData.toast(AMAttendanceActivity.this, 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(getBaseContext(), message.getMessage(), Toast.LENGTH_SHORT).show();
                    if (message.getStatus() == 401) {
                        GlobalData.canLogout = true;
                        finish();
                    }
                }
            }

            @Override
            public void onFailure(Call<CommonResponse> call, Throwable t) {

            }
        });
    }

    private void setUploadPhoto(int position, String reason) {

        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null)
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setImage(reason);
        else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent("");
            attendance.setImage(reason);
            attendance.setManualAttendanceReason("");
            attendance.setAbsenceReason("");
            attendance.setDay("");
        }

    }

    @Override
    public void onPickResult(PickResult result) {
        if (result.getError() == null) {
            IMAGE_PATH = result.getPath();
            if (IMAGE_PATH != null && !IMAGE_PATH.trim().isEmpty()) {
                Intent intent = new Intent(AMAttendanceActivity.this, CropActivity.class);
                CropActivity.mSourceUri = result.getUri();
                startActivityForResult(intent, 2276);
            } else {
                imgAttendance.setImageBitmap(result.getBitmap());
            }

        } else {
            GlobalData.showToast(this, result.getError().getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    public static ScanCallback resultCallback = new ScanCallback() {
        @Override
        public void onScanResult(String result, Context context) {
            stopScan();
            Log.e("ScanResult", result);
            if (!result.isEmpty() && result.equalsIgnoreCase(GlobalData.QRCODEVALUE)) {
                setPresentValue(GlobalData.SCANCLICKPOS, "1");
                AMAttendanceMarkingFragment.isUpdates();
            } else {
                // GlobalData.toast();
            }

            if (aDialog != null)
                aDialog.dismiss();

        }

    };

    public static void setPresentValue(int position, String reason) {
        if (singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance() != null)
            singleDateOneList.getSingleParticipantList().get(position).getSingleAttendance().setIspresent(reason);
        else {
            SingleAttendance attendance = new SingleAttendance();
            attendance.setIspresent(reason);
            attendance.setImage("");
            attendance.setManualAttendanceReason("");
            attendance.setAbsenceReason("");
            attendance.setDay("");
        }

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private static void stopScan() {
        //mScanAnimator.cancel();
        mPreviewView.stop();

    }

    @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);
    }
}