package com.offline.music.playermp3.ui.activity;

import static com.bumptech.glide.request.RequestOptions.bitmapTransform;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.lifecycle.Observer;
import androidx.media3.common.util.UnstableApi;
import androidx.recyclerview.widget.LinearLayoutManager;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.offline.music.playermp3.MusicApplication;
import com.offline.music.playermp3.R;
import com.offline.music.playermp3.adapter.AdapterCategoryList;
import com.offline.music.playermp3.api.HomeItemClickListener;
import com.offline.music.playermp3.databinding.ActivityCategoryListBinding;
import com.offline.music.playermp3.databinding.ActivityHomeBinding;
import com.offline.music.playermp3.helper.CommonUtils;
import com.offline.music.playermp3.helper.MyValue;
import com.offline.music.playermp3.javabean.response.ResponseCategoryList;
import com.offline.music.playermp3.javabean.response.ResponsePlayListInfo;
import com.offline.music.playermp3.ui.fragmnt.viewmodel.VMCategoryList;

import jp.wasabeef.glide.transformations.BlurTransformation;


/**
 * 音乐合集或者专辑列表页面
 */
public class CategoryListActivity extends BaseActivity<ActivityCategoryListBinding> implements HomeItemClickListener {


    private VMCategoryList vm;
//    private VMApplication vmApplication;

    private ResponseCategoryList mCategoryList;
    private String mPageType;
    private String twoSubtitle;
    private String browseId;

    @Override
    protected ActivityCategoryListBinding getViewBinding() {
        return ActivityCategoryListBinding.inflate(getLayoutInflater());
    }

    @Override
    protected void onCreateInit() {
        vm = getActivityScopeViewModel(VMCategoryList.class);
//        vmApplication = getApplicationScopeViewModel(VMApplication.class);
        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        mPageType=   intent.getStringExtra(MyValue.KEY_CATEGORY_LIST_TYPE);
        twoSubtitle =  intent.getStringExtra(MyValue.KEY_CATEGORY_LIST_SINGER_NAME);
        browseId =  intent.getStringExtra(MyValue.KEY_CATEGORY_LIST_BROWSER_ID);

        vb.pbLoading.setVisibility(View.VISIBLE);
        vm.getList(browseId);
        vm.data.observe(this, new Observer<ResponseCategoryList>() {
            @Override
            public void onChanged(ResponseCategoryList responseCategoryList) {
                if (responseCategoryList == null) {
                    vb.pbLoading.setVisibility(View.GONE);
                    updateErrorLayout(getString(R.string.playList_loading_failed),true);
                    return;
                }
                mCategoryList = responseCategoryList;
                loadInfo(mCategoryList);

            }
        });
    }
    private void updateErrorLayout(String msg, boolean isShow) {
        if (isShow)
            vb.layoutError.linearRetry.setVisibility(View.VISIBLE);
        else vb.layoutError.linearRetry.setVisibility(View.GONE);

        if(msg!= null&&!msg.isEmpty()){
            vb.layoutError.tvErrorMsg.setText(msg);
        }
    }
    @Override
    protected void onInitClick() {
        vb.imBack.setOnClickListener(this);
        vb.btnPlay.setOnClickListener(this);
        vb.layoutError.tvRetry.setOnClickListener(this);
    }

    @Override
    public boolean isFullScreen() {
        return true;
    }

    @Override
    public boolean statusBarLight() {
        return false;
    }

    @Override
    public boolean showPanel() {
        return true;
    }

    @Override
    public void onClick(View v) {
        if (v.equals(vb.imBack)) {
            finish();
        } else if (v.equals(vb.btnPlay)) {
            int musicIndex = 0;
            Intent intent = new Intent(this, PlayActivity.class);
            intent.putExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST, mCategoryList.getList().get(musicIndex));
//            intent.putExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST_INDEX,musicIndex);
            intent.putExtra(MyValue.KEY_ENTER_SOURCE, MyValue.TYPE_ENTER_SOURCE_CATEGORY);
            startActivity(intent);
            vmApplication.reSetPlayList(mCategoryList.getList());
        }else if(v.equals(vb.layoutError.tvRetry)){
            vb.pbLoading.setVisibility(View.VISIBLE);
            updateErrorLayout(null,false);
            vm.getList(browseId);
        }
    }

    private void loadInfo(ResponseCategoryList info) {
        vb.btnPlay.setVisibility(View.VISIBLE);
        switch (mPageType) {
            case MyValue.PAGE_TYPE_LIST:
                vb.tvSingerName.setVisibility(View.GONE);
                break;
            case MyValue.PAGE_TYPE_ALBUM:
                vb.tvSingerName.setVisibility(View.VISIBLE);
                String singNameValue = "";
                String singName = info.getSingName();
                if(singName!= null&&!singName.isEmpty()){
                    singNameValue= singName;
                }else {
                    String[] split = twoSubtitle.split("•");
                    if (split != null && split.length > 1) {
                        singNameValue = split[1];
                    }
                }
                CommonUtils.LogMsg("singNameValue=" + singNameValue);
                vb.tvSingerName.setText(singNameValue);
                for (ResponsePlayListInfo playListInfo : info.getList()) {
                    playListInfo.setSingerName(singNameValue);
                }
                break;
        }
        vb.tvTitle.setText(info.getTitle());
        vb.tvSubTitle.setText(info.getDescription());

        AdapterCategoryList adapterCategoryList = new AdapterCategoryList();
        adapterCategoryList.setHomeItemClickListener(this);
        adapterCategoryList.setPageType(mPageType);
        vb.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapterCategoryList.setData(info.getList());
        vb.recyclerview.setAdapter(adapterCategoryList);
        loadCovert(info.getCovert());

    }


    private void loadCovert(String url) {
        // 加载图片并应用高斯模糊效果
        Glide.with(this)
                .load(url)
                .apply(bitmapTransform(new BlurTransformation(25, 3))) // 设置模糊半径和模糊采样
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
                        CommonUtils.extractColorsFromImage(resource,vb.imBg);
                        return false;
                    }
                })
                .preload();


        Glide.with(MusicApplication.myApplication)
                .asDrawable()
//                .apply(bitmapTransform(new RoundedCorners(CommonUtils.dpToPx(10))))
                .load(url)
                .placeholder(R.mipmap.im_placeholder)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, @Nullable Object model, @NonNull Target<Drawable> target, boolean isFirstResource) {
                        CommonUtils.LogMsg(e.getMessage());
                        vb.pbLoading.setVisibility(View.GONE);
                        return false;
                    }

                    @OptIn(markerClass = UnstableApi.class)
                    @Override
                    public boolean onResourceReady(@NonNull Drawable resource, @NonNull Object model, Target<Drawable> target, @NonNull DataSource dataSource, boolean isFirstResource) {
//                        CommonUtils.getDominantDarkColor1(resource, new onImageColorListener() {
//                            @Override
//                            public void onImageColor(int color) {
//                                if (color == -1) {
//                                    return;
//                                }
//
//                            }
//                        });
                        vb.pbLoading.setVisibility(View.GONE);
                        return false;
                    }
                })
                .into(vb.imCovert);


    }



    @Override
    public void onClickItemCategoryList(ResponsePlayListInfo data, int musicIndex) {
        Intent intent = new Intent(this, PlayActivity.class);
        intent.putExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST, data);
        intent.putExtra(MyValue.KEY_PLAY_ACTIVITY_CATEGORY_LIST_INDEX, musicIndex);
        intent.putExtra(MyValue.KEY_ENTER_SOURCE, MyValue.TYPE_ENTER_SOURCE_CATEGORY);
        startActivity(intent);
        vmApplication.reSetPlayList(mCategoryList.getList());
    }

    @Override
    protected void onResume() {
        super.onResume();


    }
}