package com.example.mynotepad.MenuFeatures.VoiceMassages.VoiceMassagesRecyclerView;

import android.content.Context;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Handler;
import android.transition.TransitionManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;

import com.example.mynotepad.MenuFeatures.VoiceMassages.AudioListFragment;
import com.example.mynotepad.R;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.io.IOException;
import java.util.ArrayList;

public class VoiceAdaptor extends RecyclerView.Adapter<VoiceAdaptor.VoiceViewHolder> {
    private Context context;
    private ArrayList<MyVoice> myVoiceArrayList;
    private MediaPlayer mPlayer;
    private boolean isPlaying = false;
    private int last_index = -1;
    private OnVoiceMassageClickListener onVoiceMassageClickListener;
    private ImageButton playerPlayBtn;
    private TextView fileNameTv, headerTitleTv;
    private SeekBar seekBar;
    private TimeAgo timeAgo;


    public VoiceAdaptor(Context context, ArrayList<MyVoice> myVoiceArrayList, ImageButton playerPlayBtn, TextView fileNameTv, TextView headerTitleTv, SeekBar seekBar) {
        this.context = context;
        this.myVoiceArrayList = myVoiceArrayList;
        this.playerPlayBtn = playerPlayBtn;
        this.fileNameTv = fileNameTv;
        this.headerTitleTv = headerTitleTv;
        this.seekBar = seekBar;
        timeAgo= new TimeAgo();
    }

    @NonNull
    @Override
    public VoiceViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.custom_voice_item, parent, false);
        return new VoiceViewHolder(view);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    @Override
    public void onBindViewHolder(@NonNull VoiceViewHolder holder, int position) {
        setUpData(holder, position);
    }


    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void setUpData(VoiceViewHolder holder, int position) {

        MyVoice myVoice = myVoiceArrayList.get(position);
        holder.textViewName.setText(myVoice.getFileName());
        holder.textLongAgo.setText(timeAgo.getTimeAgo(myVoice.getLastModified()));

        if (myVoice.isPlaying()) {
            holder.imageViewStop.setVisibility(View.VISIBLE);
            holder.imageViewPlay.setVisibility(View.GONE);
            headerTitleTv.setText("playing");
            playerPlayBtn.setImageDrawable(context.getResources().getDrawable(R.drawable.white_play_arrow));
            TransitionManager.beginDelayedTransition((ViewGroup) holder.itemView);
            holder.seekUpdation(holder);
        } else {
            headerTitleTv.setText("not playing");
            holder.imageViewStop.setVisibility(View.GONE);
            holder.imageViewPlay.setVisibility(View.VISIBLE);
            playerPlayBtn.setImageDrawable(context.getResources().getDrawable(R.drawable.white_pause));
            TransitionManager.beginDelayedTransition((ViewGroup) holder.itemView);
        }

        holder.manageSeekBar(holder);

    }

    @Override
    public int getItemCount() {
        return myVoiceArrayList.size();
    }

    public void setOnVoiceMassageClickListener(OnVoiceMassageClickListener onVoiceMassageClickListener) {
        this.onVoiceMassageClickListener = onVoiceMassageClickListener;
    }


    class VoiceViewHolder extends RecyclerView.ViewHolder implements View.OnLongClickListener {
        private FrameLayout startStopBtn;
        private ImageView imageViewPlay, imageViewStop;
        private TextView textViewName , textLongAgo;
        private String recordingUri;
        private Handler seekBarHandler = new Handler();
        private VoiceViewHolder holder;
        private int playingPosition;

        public VoiceViewHolder(View itemView) {
            super(itemView);

            imageViewPlay = itemView.findViewById(R.id.playImg);
            imageViewStop = itemView.findViewById(R.id.pauseImg);
            textViewName = itemView.findViewById(R.id.voiceName);
            textLongAgo = itemView.findViewById(R.id.voiceTime);
            startStopBtn = itemView.findViewById(R.id.start_stopBtn);
            imageViewStop.setVisibility(View.GONE);
            playerPlayBtn.setImageDrawable(context.getResources().getDrawable(R.drawable.white_play_arrow));

            addListener();

        }

        private void addListener() {
            itemView.setOnLongClickListener(this);
            //add clickListener to stop or start playing
            startStopBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    playingPosition = getAdapterPosition();
                    startAndStopPlaying(playingPosition);
                }
            });

            playerPlayBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    startAndStopPlaying(playingPosition);
                }
            });

        }

        private void startAndStopPlaying(int position) {

            MyVoice myVoice = myVoiceArrayList.get(position);
            recordingUri = myVoice.getUri();
            fileNameTv.setText(myVoice.getFileName());

            //if media player is playing
            if (isPlaying) {
                stopPlaying();
                //if another clicked item (your last chosen item) is playing and you click on it again to stop it
                if (position == last_index) {
                    myVoice.setPlaying(false);
                    stopPlaying();
                    notifyItemChanged(position);
                }
                // if you click on another item while your last one(your last chosen item) is playing
                else {
                    markAllPaused();
                    myVoice.setPlaying(true);
                    notifyItemChanged(position);
                    startPlaying(myVoice, position);
                    last_index = position;// set the last playing item on the one which is playing
                }
            }
            //if media player is not playing
            else {
                //if clicked item is playing it is wrong so it should be stopped
                if (myVoice.isPlaying()) {
                    myVoice.setPlaying(false);
                    stopPlaying();
                    Log.d("isPlayin", "True");
                }
                //if nothing is playing and you want to play a new voice massage
                else {
                    startPlaying(myVoice, position);
                    myVoice.setPlaying(true);
                    // seekBar.setMax(mPlayer.getDuration());
                    Log.d("isPlayin", "False");
                }
                notifyItemChanged(position);
                last_index = position;// set the last playing item on the one which is playing
            }

        }

        private void stopPlaying() {
            try {
                mPlayer.release();
            } catch (Exception e) {
                e.printStackTrace();
            }
            mPlayer = null;
            isPlaying = false;
        }

        private void startPlaying(final MyVoice audio, final int position) {
            AudioListFragment.bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);// when u choose an item media player will open automatically
            mPlayer = new MediaPlayer();
            try {
                mPlayer.setDataSource(recordingUri);
                mPlayer.prepare();
                mPlayer.start();
            } catch (IOException e) {
                Log.e("LOG_TAG", "prepare() failed");
            }
            //showing the pause button
            seekBar.setMax(mPlayer.getDuration());
            isPlaying = true;

            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mp) {
                    audio.setPlaying(false);
                    notifyItemChanged(position);
                }
            });

            mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                @Override
                public void onCompletion(MediaPlayer mediaPlayer) {
                    stopPlaying();
                    playerPlayBtn.setImageDrawable(context.getResources().getDrawable(R.drawable.white_play_arrow));
                    headerTitleTv.setText("finished");
                }
            });
        }

        public void manageSeekBar(VoiceViewHolder holder) {
            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    if (mPlayer != null && fromUser) {
                        mPlayer.seekTo(progress);
                    }
                    seekBar.postDelayed(runnable, 0);
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {
                }
            });
        }

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                seekUpdation(holder);
            }
        };

        private void seekUpdation(VoiceViewHolder holder) {
            this.holder = holder;
            if (mPlayer != null) {
                int mCurrentPosition = mPlayer.getCurrentPosition();
                seekBar.setMax(mPlayer.getDuration());
                seekBar.setProgress(mCurrentPosition);
            }
            seekBarHandler.postDelayed(runnable, 0);
        }

        /*
         * set all voice items on pause and stop all of them
         */
        private void markAllPaused() {
            for (int i = 0; i < myVoiceArrayList.size(); i++) {
                myVoiceArrayList.get(i).setPlaying(false);
                myVoiceArrayList.set(i, myVoiceArrayList.get(i));
            }
            notifyDataSetChanged();
        }

        @Override
        public boolean onLongClick(View view) {
            if (onVoiceMassageClickListener != null)
                onVoiceMassageClickListener.onItemLongClicked(myVoiceArrayList.get(getAdapterPosition()));
            return true;
        }
    }

}
