package com.keyboard.theme.app.keyboard.ui;

import static com.keyboard.theme.app.keyboard.utils.StaticValue.KEYTheme;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.keyboard.theme.app.keyboard.MyAppllication;
import com.keyboard.theme.app.keyboard.R;
import com.keyboard.theme.app.keyboard.data.InfoChild;
import com.keyboard.theme.app.keyboard.databinding.ActivityApplyBinding;
import com.keyboard.theme.app.keyboard.utils.Common;
import com.keyboard.theme.app.keyboard.utils.FileManager;
import com.keyboard.theme.app.keyboard.utils.StaticValue;
import com.keyboard.theme.app.keyboard.utils.StepManager;

import java.io.File;

public class ActivityApply extends BaseActivity<ActivityApplyBinding> implements View.OnClickListener {

    private InfoChild infoChild;
    private String unZipPath;

    private ActivityApplyBinding bind;
    private ActivityStep dialogStep;

    @NonNull
    @Override
    public ActivityApplyBinding returnViewbinding() {
        Common.INSTANCE.initFull(this, false);
        return ActivityApplyBinding.inflate(getLayoutInflater());
    }

    @Override
    public void onInit() {
        bind = getVb();
        Common.INSTANCE.setFont(bind.idSet);
        Common.INSTANCE.setFont( bind.idTheme);
        Intent intent = getIntent();
        infoChild = (InfoChild) intent.getSerializableExtra(KEYTheme);
        File cacheDir = MyAppllication.instance.getCacheDir();
        String unZip = FileManager.INSTANCE.getUnZip(infoChild.getTitle());

        unZipPath = cacheDir + "/" + unZip;

        bind.idTheme.setText(infoChild.getTitle());

        initText();
        initListener();
        loadPreview();
    }


    private void initListener() {
        bind.idBack.setOnClickListener(this);
        bind.idSet.setOnClickListener(this);
    }

    private void initText() {
        File file = new File(unZipPath);
        if (!file.exists()) {
            bind.idSet.setText(getString(R.string.text_text_download_apply));
        } else {
            bind.idSet.setText(getString(R.string.text_text_apply));
        }

    }

    private void loadPreview() {
        bind.idPreloading.setVisibility(View.VISIBLE);
        Glide.with(ActivityApply.this).load(infoChild.getPreview())
                .placeholder(ContextCompat.getDrawable(this, R.mipmap.placholder))
                .addListener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        bind.idPreloading.setVisibility(View.GONE);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        bind.idPreloading.setVisibility(View.GONE);
                        return false;
                    }
                })
                .transform(new RoundedCorners(Common.INSTANCE.dpToUnitPx(10f)))
                .into(bind.idImage);


    }

    @Override
    protected void onResume() {
        super.onResume();
        if(dialogStep!= null){
            dialogStep.updateUi();
        }

    }

    private void onapply() {
        if (!StepManager.INSTANCE.toEnable() || !StepManager.INSTANCE.onsetInput()) {
            if(dialogStep == null){
                dialogStep = new ActivityStep(this);
            }
            if(!dialogStep.isAdded()){
                dialogStep.show(getSupportFragmentManager(),"");
            }
            return;
        }
        bind.idProgressbar.setVisibility(View.VISIBLE);
        File file = new File(unZipPath);
        if (file.exists()) {
            String allThemePath = Common.INSTANCE.getAllThemePath(infoChild.getTitle());
          if(allThemePath != null){
              Common.INSTANCE.putCurPath(allThemePath);
          }
            bind.idProgressbar.setVisibility(View.GONE);
            Toast.makeText(this, getString(R.string.text_succ_apply), Toast.LENGTH_LONG).show();
            goSuccess();
            finish();
        } else {
            FileManager.INSTANCE.getZipData(infoChild.getTitle(), infoChild.getZipUrl(), this, this::onResult) ;

        }


    }

    private void onResult(Boolean isSuccess, String path){
        bind.idProgressbar.setVisibility(View.GONE);
        if (isSuccess) {
            int lastIndexOf = path.lastIndexOf(StaticValue.INSTANCE.getRes_path());
            String substring = path.subSequence(0, lastIndexOf + StaticValue.INSTANCE.getRes_path().length()).toString();
            Common.INSTANCE.putCurPath(substring);
            Common.INSTANCE.putAllThemePath(infoChild.getTitle(), substring);
            Toast.makeText(this, getString(R.string.text_succ_apply), Toast.LENGTH_LONG).show();
            goSuccess();
            finish();
        } else {
            Toast.makeText(this, getString(R.string.text_fail_apply), Toast.LENGTH_LONG).show();
        }
    }


    private void goSuccess(){
        Intent intent = new Intent(this, SuccessActivity.class);
        intent.putExtra(SuccessActivity.key_name,infoChild.getTitle());
        startActivity(intent);
    }
    @Override
    public void onClick(View v) {
        if (v.equals(bind.idBack)) {
            finish();
        } else if (v.equals(bind.idSet)) {
            onapply();
        }

    }
}
