package com.tencent.liteav.demo.player;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.android.cast.dlna.dmc.DLNACastManager;
import com.android.cast.dlna.dmc.OnDeviceRegistryListener;
import com.tencent.liteav.demo.player.databinding.ActivityCastBinding;
import com.tencent.liteav.demo.player.ui.PlayerCastAdapter;
import com.tencent.liteav.demo.superplayer.util.CastorUtil;

import org.fourthline.cling.model.meta.Device;

public class PlayerCast extends AppCompatActivity implements OnDeviceRegistryListener {
    private ActivityCastBinding viewBinding;

    private PlayerCastAdapter adapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        viewBinding = ActivityCastBinding.inflate(getLayoutInflater());
        setContentView(viewBinding.getRoot());

        adapter = new PlayerCastAdapter(new PlayerCastAdapter.OnItemSelectedListener() {
            @Override
            public void onItemSelected(@Nullable Device<?, ?, ?> castDevice, boolean selected) {
                CastorUtil.INSTANCE.selectDevice(castDevice);
                PlayerCast.this.finish();
            }
        });
        viewBinding.castDevice.setAdapter(adapter);
        viewBinding.castCancel.setOnClickListener((v) -> {
            finish();
        });
        viewBinding.castHelper.setOnClickListener((v) -> {
            Intent intent = new Intent(this, CastHelpActivity.class);
            startActivity(intent);
        });
        viewBinding.castClose.setOnClickListener((v) -> {
            finish();
        });

        DLNACastManager.getInstance().registerDeviceListener(adapter);
        DLNACastManager.getInstance().registerDeviceListener(this);

        DLNACastManager.getInstance().search(null, 60);
    }

    @Override
    protected void onDestroy() {
        DLNACastManager.getInstance().unregisterListener(adapter);
        DLNACastManager.getInstance().unregisterListener(this);
        super.onDestroy();

        viewBinding = null;
    }

    @Override
    public void onDeviceAdded(Device<?, ?, ?> device) {
        if (viewBinding.castDevice.getVisibility() != View.VISIBLE) {
            viewBinding.castDevice.setVisibility(View.VISIBLE);
            viewBinding.castLoading.setVisibility(View.GONE);
        }
    }

    @Override
    public void onDeviceUpdated(Device<?, ?, ?> device) {

    }

    @Override
    public void onDeviceRemoved(Device<?, ?, ?> device) {

    }
}
