package com.photo.keyboard.themes.pager;

import static com.photo.keyboard.themes.manager.ConstValue.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.photo.keyboard.themes.App;
import com.photo.keyboard.themes.R;
import com.photo.keyboard.themes.data.ThemeData;
import com.photo.keyboard.themes.databinding.ActivitySetThemesBinding;
import com.photo.keyboard.themes.manager.ConstValue;
import com.photo.keyboard.themes.manager.DbManager;
import com.photo.keyboard.themes.manager.EnableActive;
import com.photo.keyboard.themes.manager.FileDeal;
import com.photo.keyboard.themes.manager.Utils;
import com.photo.keyboard.themes.topon.AdManager;
import com.photo.keyboard.themes.topon.onActionListener;

import java.io.File;

public class SetThemesActivity extends BaseActivity<ActivitySetThemesBinding> implements View.OnClickListener {

    private ThemeData themeData;
    private String unZipPath;

    private ActivitySetThemesBinding bind;
    private DialogEnable dialogStep;

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

    @Override
    public void onInit() {
        bind = getVb();
        AdManager.loadAllAd();
        Utils.INSTANCE.setFont(bind.idSet);
        Utils.INSTANCE.setFont(bind.idTheme);
        Intent intent = getIntent();
        themeData = (ThemeData) intent.getSerializableExtra(KEYTheme);
        File cacheDir = App.instance.getCacheDir();
        String unZip = FileDeal.INSTANCE.getUnZip(themeData.getTitle());

        unZipPath = cacheDir + "/" + unZip;

        bind.idTheme.setText(themeData.getTitle());
        bind.btnLike.setSelected(DbManager.queryIsLike(themeData.getResId()));

        AdManager.showTopOn(SetThemesActivity.this, new onActionListener() {
            @Override
            public void onAction() {

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


    private void initListener() {
        bind.idBack.setOnClickListener(this);
        bind.idSet.setOnClickListener(this);
        bind.btnLike.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(SetThemesActivity.this).load(themeData.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(Utils.INSTANCE.dpToUnitPx(10f)))
                .into(bind.idImage);


    }

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

    }

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

        }


    }

    private void onResult(Boolean isSuccess, String path) {
        bind.idProgressbar.setVisibility(View.GONE);
        if (isSuccess) {
            int lastIndexOf = path.lastIndexOf(ConstValue.INSTANCE.getRes_path());
            String substring = path.subSequence(0, lastIndexOf + ConstValue.INSTANCE.getRes_path().length()).toString();
            Utils.INSTANCE.putCurPath(substring);
            Utils.INSTANCE.putAllThemePath(themeData.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, themeData.getTitle());
        startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if (v.equals(bind.idBack)) {
            finish();
        } else if (v.equals(bind.idSet)) {
            AdManager.showTopOn(SetThemesActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    onapply();
                }
            });

        } else if (v.equals(bind.btnLike)) {
            AdManager.showTopOn(SetThemesActivity.this, new onActionListener() {
                @Override
                public void onAction() {
                    bind.btnLike.setSelected(!bind.btnLike.isSelected());
                    if (bind.btnLike.isSelected()) {
                        DbManager.addLike(themeData);
                    } else {
                        DbManager.deleteLike(themeData);
                    }
                }
            });

        }

    }
}
