package com.hi.music.player.ui.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.OptIn;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.WindowCompat;
import androidx.core.view.WindowInsetsControllerCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModel;
import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.viewbinding.ViewBinding;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.hi.music.player.MusicApplication;
import com.hi.music.player.R;
import com.hi.music.player.api.onPlayNextListener;
import com.hi.music.player.databinding.ActivityBaseBinding;
import com.hi.music.player.databinding.LayoutPanelBinding;
import com.hi.music.player.helper.CommonUtils;
import com.hi.music.player.helper.MyValue;
import com.hi.music.player.helper.ViewModelScope;
import com.hi.music.player.media3.MyMediaControllerManager;
import com.hi.music.player.ui.activity.viewmodel.VMApplication;

public abstract class BaseActivity<T extends ViewBinding> extends AppCompatActivity implements View.OnClickListener {

    private final ViewModelScope mViewModelScope = new ViewModelScope();

    protected T vb;

    private Window window;
    private View decorView;
    protected View mView;
    private ActivityBaseBinding rootVb;

    protected VMApplication vmApplication;
    protected MyMediaControllerManager mediaControllerManager;

    private Handler mHandler;
    private Runnable mRunnable;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        vb = getViewBinding();
        View root = vb.getRoot();
        rootVb = ActivityBaseBinding.inflate(getLayoutInflater(), null, false);
        rootVb.frameLayout.addView(root);
        setContentView(rootVb.getRoot());
        window = getWindow();
        decorView = window.getDecorView();
        mView = decorView.getRootView();
        vmApplication = getApplicationScopeViewModel(VMApplication.class);
        mediaControllerManager = MyMediaControllerManager.getInstance();

        if (showPanel())
            initPanel();
        setStatusBar();
        if (isFullScreen()) {
//            ImmersionBar.with(this).init();//设置沉浸式效果
//            ImmersionBar.setStatusBarView(this,0);
            initFullScreen();
        }
        onCreateInit();
        onInitClick();
    }

    protected abstract T getViewBinding();


    protected abstract void onCreateInit();

    protected abstract void onInitClick();

    public abstract boolean isFullScreen();

    public abstract boolean statusBarLight();

    public abstract boolean showPanel();



    private void initPanel() {
        LayoutPanelBinding panelVb = LayoutPanelBinding.inflate(getLayoutInflater());
        View panelView = panelVb.getRoot();
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                FrameLayout.LayoutParams.MATCH_PARENT,
                CommonUtils.dpToPx(74)
        );
        initProgressHandler(panelVb);
        panelVb.imPlay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                panelVb.imPlay.setSelected(!panelVb.imPlay.isSelected());
                if (panelVb.imPlay.isSelected()) {
                    mediaControllerManager.play();
                } else {
                    mediaControllerManager.pause();
                }

            }
        });
        panelVb.imNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mediaControllerManager.playNext(new onPlayNextListener() {
                    @Override
                    public void onPlayNext(boolean hasNext) {
                        if (!hasNext) {
                            Toast.makeText(MusicApplication.myApplication, getString(R.string.no_next_song_yet), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
        panelVb.layoutPanel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MusicApplication.myApplication, PlayActivity.class);
                intent.putExtra(MyValue.KEY_ENTER_SOURCE, MyValue.TYPE_ENTER_PANEL);
                startActivity(intent);
            }
        });

        if (this instanceof HomeActivity) {
            layoutParams.setMargins(CommonUtils.dpToPx(22), 0, CommonUtils.dpToPx(22), CommonUtils.dpToPx(82));
        } else {
            layoutParams.setMargins(CommonUtils.dpToPx(22), 0, CommonUtils.dpToPx(22), CommonUtils.dpToPx(10));
        }

        layoutParams.gravity = Gravity.BOTTOM;
        vmApplication.playStatus.observe(this, new Observer<Integer>() {
            @OptIn(markerClass = UnstableApi.class)
            @Override
            public void onChanged(Integer integer) {
                CommonUtils.LogMsg("----------面板 播放状态更新=" + integer);
                if (panelView.getParent() == null) {
                    CommonUtils.LogMsg("----------显示面板");
                    rootVb.frameLayout.addView(panelView, layoutParams);
                    mHandler.post(mRunnable);
                }
                MediaItem currentMediaItem = mediaControllerManager.getCurMediaItem();
                if(currentMediaItem!= null){
                    Uri artworkUri = currentMediaItem.mediaMetadata.artworkUri;
                    CharSequence title = currentMediaItem.mediaMetadata.title;
                    CharSequence artist = currentMediaItem.mediaMetadata.artist;

                    if (currentMediaItem.mediaMetadata.durationMs != null) {
                        long durationMs = currentMediaItem.mediaMetadata.durationMs;
                        panelVb.circularPb.setMaxProgress((int) durationMs);
                    }
                    if(artworkUri!= null){
                        CommonUtils.LogMsg("----------artworkUri="+artworkUri.toString());
                        Glide.with(MusicApplication.myApplication)
                                .load(artworkUri.toString())
                                .placeholder(R.mipmap.im_placeholder)
                                .transform(new CircleCrop())
                                .into(panelVb.image);
                    }
                    panelVb.title.setText(title);
                    panelVb.singer.setText(artist);
                }

                switch (integer) {
                    case Player.STATE_IDLE:

                    case Player.STATE_ENDED:
                    case Player.STATE_READY:

                    case MyValue.PLAY_STATUS_CODE_PAUSE:
                    case Player.STATE_BUFFERING:
                    case MyValue.PLAY_STATUS_CODE_ERROR:

                        //快进没有缓冲的时候触发
                        //播放完成
                        panelVb.imPlay.setSelected(false);
                        break;
                    case MyValue.PLAY_STATUS_CHANGE_MUSIC:
                    case MyValue.PLAY_STATUS_CODE_PLAYING:
                        panelVb.imPlay.setSelected(true);
                        break;

                }

            }
        });


    }


    private void initProgressHandler(LayoutPanelBinding panelBinding) {
        mHandler = new Handler();
        mRunnable = new Runnable() {
            @Override
            public void run() {
                updatePlaybackProgress(panelBinding);
                mHandler.postDelayed(this, 1000);
            }
        };
    }

    private void updatePlaybackProgress(LayoutPanelBinding panelBinding) {
        // 获取当前播放位置
        long contentPos = mediaControllerManager.getContentPos();
        long bufferPos = mediaControllerManager.getBufferPos();

//        CommonUtils.LogMsg("---------播放进度-----contentPos=" + contentPos + "-----缓冲进度=" + bufferPos);
        panelBinding.circularPb.setProgress((int) contentPos);
    }
    private void setStatusBar() {
        //深色模式
        WindowInsetsControllerCompat insetsController = WindowCompat.getInsetsController(getWindow(), getWindow().getDecorView());
        insetsController.setAppearanceLightStatusBars(statusBarLight());
    }

    private void initFullScreen() {
        decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
//        mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
        mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    }

    protected <K extends ViewModel> K getActivityScopeViewModel(@NonNull Class<K> modelClass) {
        return mViewModelScope.getActivityScopeViewModel(this, modelClass);
    }

    protected <K extends ViewModel> K getApplicationScopeViewModel(@NonNull Class<K> modelClass) {
        return mViewModelScope.getApplicationScopeViewModel(modelClass);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null && mRunnable != null)
            mHandler.removeCallbacks(mRunnable);
    }
}