package com.cjt2325.cameralibrary;

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.appcompat.widget.AppCompatSeekBar;

import com.cjt2325.cameralibrary.listener.ClickListener;

import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;


/**
 * =====================================
 * 作    者: 陈嘉桐 445263848@qq.com
 * 版    本：1.0.4
 * 创建日期：2017/4/26
 * 描    述：集成各个控件的布局
 * =====================================
 */

public class PlaybackLayout extends LinearLayout {

    private Context mContext;

    private ImageView btnPlay;
    private ImageView btnPause;
    private TextView textProgress;
    private TextView textDuration;
    private AppCompatSeekBar seekBar;
    private LinearLayout layoutCLose;
    private ImageView btnClose;
    private ImageView btnFullScreen;

    private int progress;         //视频的进度
    private int duration;           //视频的时长
    private boolean isChanging = false;     //互斥变量，防止定时器与SeekBar拖动时进度冲突

    private ClickListener playListener;
    private ClickListener pauseListener;
    private ClickListener closeListener;
    private ClickListener fullScreenListener;
    private SeekChangedListener seekChangedListener;
    private ProgressCallback progressCallback;

    private Timer mTimer;
    private TimerTask mTimerTask;

    public interface SeekChangedListener {
        void onSeek(int progress);
    }

    public interface ProgressCallback {
        void updateProgress();
    }

    public PlaybackLayout(Context context) {
        this(context, null);
    }

    public PlaybackLayout(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PlaybackLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mContext = context;

        initView();
    }

    private void initView() {
        inflate(mContext, R.layout.playback_view, this);
        init();
        resetPlaybackLayout();
    }

    private void init() {
        btnPlay = findViewById(R.id.image_play);
        btnPause = findViewById(R.id.image_pause);
        textProgress = findViewById(R.id.text_progress);
        textDuration = findViewById(R.id.text_duration);
        seekBar = findViewById(R.id.seek_bar);
        layoutCLose = findViewById(R.id.layout_close);
        btnClose = findViewById(R.id.image_close);
        btnFullScreen = findViewById(R.id.image_full_screen);

        LayerDrawable layerDrawable = (LayerDrawable) seekBar.getProgressDrawable();
        Drawable secondDrawable = layerDrawable.getDrawable(2);
        secondDrawable.setColorFilter(getResources().getColor(android.R.color.darker_gray), PorterDuff.Mode.SRC);

        Drawable firstDrawable = layerDrawable.getDrawable(1);
        firstDrawable.setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC);

        Drawable thumbDrawable = seekBar.getThumb();
        thumbDrawable.setColorFilter(getResources().getColor(android.R.color.white), PorterDuff.Mode.SRC_ATOP);
        seekBar.invalidate();

        btnPlay.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                btnPause.setVisibility(VISIBLE);
                btnPlay.setVisibility(GONE);
                setTimerForProgress();
                if (playListener != null)
                    playListener.onClick();
            }
        });

        btnPause.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                onPause();
                if (pauseListener != null)
                    pauseListener.onClick();
            }
        });

        btnClose.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mTimer != null)
                    mTimer.cancel();
                if (closeListener != null)
                    closeListener.onClick();
            }
        });

        btnFullScreen.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (fullScreenListener != null)
                    fullScreenListener.onClick();
            }
        });

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isChanging = true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (seekChangedListener != null) {
                    int progress = seekBar.getProgress();
                    seekChangedListener.onSeek(progress);
                }
                isChanging = false;
            }
        });
    }

    /**************************************************
     * 对外提供的API                      *
     **************************************************/
    public void resetPlaybackLayout() {
        btnPause.setVisibility(GONE);
        btnPlay.setVisibility(VISIBLE);
        textProgress.setText("00:00");
        seekBar.setProgress(0);
    }

    public void resetTimer() {
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    public void onPause() {
        btnPlay.setVisibility(VISIBLE);
        btnPause.setVisibility(GONE);
    }

    public void setDuration(int duration) {
        resetPlaybackLayout();

        btnPause.setVisibility(VISIBLE);
        btnPlay.setVisibility(GONE);

        this.duration = duration;
        seekBar.setMax(duration);

        String strText = "00:00";
        if (duration > 0) {
            int duration_s = Math.round((float) duration / 1000);
            strText = String.format(Locale.CHINA, "%02d:%02d", duration_s / 60, duration_s % 60);
        }
        textDuration.setText(strText);
        setTimerForProgress();
    }

    public void setProgress(int progress) {
        if (isChanging)
            return;

        this.progress = progress;
        seekBar.setProgress(progress);

        String strText = "00:00";
        if (progress > 0) {
            int progress_s = Math.round(progress / 1000);
            strText = String.format(Locale.CHINA, "%02d:%02d", progress_s / 60, progress_s % 60);
        }
        textProgress.setText(strText);
    }

    private void setTimerForProgress() {
        if (mTimer == null) {
            mTimer = new Timer();
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    if (progressCallback != null) {
                        progressCallback.updateProgress();
                    }
                }
            };
            mTimer.schedule(mTimerTask, 0, 50);
        }
    }

    public void setPlayClickListener(ClickListener clickListener) {
        this.playListener = clickListener;
    }

    public void setPauseClickListener(ClickListener clickListener) {
        this.pauseListener = clickListener;
    }

    public void setCloseClickListener(ClickListener clickListener) {
        this.closeListener = clickListener;
    }

    public void setFullScreenClickListener(ClickListener clickListener) {
        this.fullScreenListener = clickListener;
    }

    public void setSeekChangedListener(SeekChangedListener seekChangedListener) {
        this.seekChangedListener = seekChangedListener;
    }

    public void setProgressCallback(ProgressCallback progressCallback) {
        this.progressCallback = progressCallback;
    }

    public void setShowBtnClose(boolean show) {
        layoutCLose.setVisibility(show ? VISIBLE : GONE);
    }

    public void setShowBtnFullScreen(boolean show) {
        btnFullScreen.setVisibility(show ? VISIBLE : GONE);
    }
}
