package com.ez.ertc.meeting.service;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.provider.Settings;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatImageView;

import com.ez.ertc.meeting.R;
import com.ez.ertc.meeting.constant.SharingType;
import com.ez.ertc.meeting.utils.AndroidUtil;
import com.ez.ertc.meeting.utils.ViewUtil;
import com.ez.ertc.meeting.widget.ErtcTextureView;
import com.ez.ertc.meeting.widget.TextCircleImageView;
import com.ez.ertcmeeting.bean.DeviceState;
import com.ez.ertcmeeting.bean.UserAccount;

public class ErtcPictureInPictureService extends Service {
    private WindowManager windowManager;
    private WindowManager.LayoutParams layoutParams;

    private View contView;
    private ErtcTextureView pInPTextureView;
    private PInPBinder pInPBinder;
    private AppCompatImageView ivAudioState;
    private TextView tvName;
    private FrameLayout flAvatar;
    private TextCircleImageView ivAvatar;
    private int mScreenWidth;

    @Override
    public void onCreate() {
        super.onCreate();
        Configuration mConfiguration = this.getResources().getConfiguration(); //获取设置的配置信息
        if (mConfiguration.orientation == mConfiguration.ORIENTATION_LANDSCAPE) {
            mScreenWidth = AndroidUtil.getScreenHeight(this);
        } else {
            mScreenWidth = AndroidUtil.getScreenWidth(this);
        }
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);

        layoutParams = new WindowManager.LayoutParams();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        }
        //layoutParams.format = PixelFormat.RGBA_8888;
        layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        layoutParams.width = ViewUtil.dp2px(this,90);
        layoutParams.height = ViewUtil.dp2px(this,160);
        layoutParams.x = mScreenWidth - ViewUtil.dp2px(this,90);
        layoutParams.y = 50;

        showFloatingWindow();
    }

    @Override
    public IBinder onBind(Intent intent) {
        if (pInPBinder == null) {
            pInPBinder = new PInPBinder();
        }
        return pInPBinder;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        removeFloating();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    private void showFloatingWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (Settings.canDrawOverlays(this)) {
                contView = View.inflate(getApplicationContext(), R.layout.ertc_room_pinp, null);
                pInPTextureView = contView.findViewById(R.id.pInPTextureView);
                ivAudioState = contView.findViewById(R.id.ivAudioState);
                tvName = contView.findViewById(R.id.tvName);
                flAvatar = contView.findViewById(R.id.flAvatar);
                ivAvatar = contView.findViewById(R.id.ivAvatar);
                contView.setOnTouchListener(new FloatingOnTouchListener());
                windowManager.addView(contView, layoutParams);

            }
        }
    }

    private void removeFloating() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (windowManager != null && contView != null) {
                windowManager.removeView(contView);
            }
        }
    }

    @SuppressLint("NewApi")
    private void animToEdge(final View view){
        ValueAnimator animator;
        if (layoutParams.x + contView.getWidth() / 2 > mScreenWidth / 2){
            animator = ValueAnimator.ofInt(layoutParams.x, mScreenWidth - contView.getWidth());
        } else {
            animator = ValueAnimator.ofInt(layoutParams.x, 0);
        }
        animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                layoutParams.x = (int) animation.getAnimatedValue();
                windowManager.updateViewLayout(view, layoutParams);
            }
        });
        animator.setDuration(150);
        animator.start();
    }

    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;
        private int xDown;
        private int yDown;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    xDown = (int) event.getRawX();
                    yDown = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    layoutParams.x = layoutParams.x + movedX;
                    layoutParams.y = layoutParams.y + movedY;
                    windowManager.updateViewLayout(view, layoutParams);
                    break;
                case MotionEvent.ACTION_UP:
                    int xUp = (int) event.getRawX();
                    int yUp = (int) event.getRawY();
                    if (Math.abs(xUp - xDown) < 10 && Math.abs(yUp - yDown) < 10){
                        if (pInPBinder != null) {
                            pInPBinder.getOnCloseListener().onClose();
                        }
                    } else {
                        animToEdge(view);
                    }
                    break;
                default:
                    break;
            }
            return false;
        }
    }

    public class PInPBinder extends Binder {
        private OnCloseListener onCloseListener;

        public OnCloseListener getOnCloseListener() {
            return onCloseListener;
        }

        public void setOnCloseListener(OnCloseListener onCloseListener) {
            this.onCloseListener = onCloseListener;
        }

        public ErtcTextureView getTextureView() {
            return pInPTextureView;
        }

        public void setAccount(UserAccount account, SharingType sharingType) {
            if (ivAudioState != null) {
                ivAudioState.setImageResource(account.getAudioStatus() == DeviceState.DS_Active.getValue() ?
                        R.drawable.ys_mt_svg_audio_on_33_30dp : R.drawable.ys_mt_svg_audio_off_33_30dp);
                tvName.setText(account.getUserId());
                //共享时不关闭视频
                if (account.getVideoStatus() == DeviceState.DS_Active.getValue() || sharingType == SharingType.ST_Desktop){
                    pInPTextureView.setVisibility(View.VISIBLE);
                    flAvatar.setVisibility(View.GONE);
                } else {
                    ivAvatar.setImageDrawable(null);
                    ivAvatar.setText(account.getUserId());
//                    String portrait = MeetingUtil.getPortraitFromAccount(account);
//                    if (!TextUtils.isEmpty(portrait)){
//                        Glide.with(ErtcPictureInPictureService.this)
//                            .load(portrait)
//                            .into(ivAvatar);
//                    }
                    flAvatar.setVisibility(View.VISIBLE);
                    pInPTextureView.setVisibility(View.GONE);
                }
            }
        }
    }

    public interface OnCloseListener {
        void onClose();
    }
}
