package kr.co.compcareworker.Util.CustomView;

import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import java.util.Timer;
import java.util.TimerTask;

import kr.co.compcareworker.MyApplication;
import kr.co.compcareworker.R;

public class MyProgress extends Dialog {

    private Context context;
    private TextView txtProgress;
    private ProgressBar progressBar;
    private TextView progressCnt;
    private int pStatus = 0;
    private int total = 0;
    private int cnt = 0;
    Timer timer;

    public MyProgress(@NonNull Context context, int total) {
        super(context);
        this.total = total;
        this.context = context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dlg_prograss_bar);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        setCanceledOnTouchOutside(false);
        setCancelable(false);

        txtProgress = findViewById(R.id.progress_text);
        progressBar = findViewById(R.id.progress_bar);
        progressCnt = findViewById(R.id.progress_cnt);

    }

    @Override
    protected void onStop() {
        timer.cancel();
        super.onStop();
    }

    public void setPercent(int percent, int i) {
        pStatus = percent;
        cnt = i;

        progressBar.setProgress(((percent + (cnt * 100)) / total));
        txtProgress.setText(((percent + (cnt * 100)) / total) + " %");
        progressCnt.setText((cnt + 1) + " / " + total);

        if (MyApplication.uploadError) {
            Toast.makeText(context, "사진 업로드에 실패했습니다.", Toast.LENGTH_SHORT);
            dismiss();
        }
    }

    public void closeDialog() {
        Toast.makeText(context, "오류가 발생했습니다.", Toast.LENGTH_SHORT);
        dismiss();
    }

    public void uploadFinish() {

        if (((pStatus + (cnt * 100)) / total) == 100) {
            timer = new Timer();
            timer.schedule(new CustomTimer(), 500, 500);
        }
    }

    class CustomTimer extends TimerTask {
        @Override
        public void run() {
            if (MyApplication.uploadFinish) {
                dismiss();
                timer.cancel();
            }
        }
    }
}