package com.example.mynotepad.MenuFeatures.VoiceMassages;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

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.SeekBar;
import android.widget.TextView;

import com.example.mynotepad.MenuFeatures.CustomToolbarOption;
import com.example.mynotepad.MenuFeatures.CustomToolbarOptionListener;
import com.example.mynotepad.MenuFeatures.VoiceMassages.VoiceMassagesRecyclerView.MyVoice;
import com.example.mynotepad.MenuFeatures.VoiceMassages.VoiceMassagesRecyclerView.OnVoiceMassageClickListener;
import com.example.mynotepad.MenuFeatures.VoiceMassages.VoiceMassagesRecyclerView.VoiceAdaptor;
import com.example.mynotepad.R;
import com.google.android.material.bottomsheet.BottomSheetBehavior;

import java.io.File;
import java.util.ArrayList;


public class AudioListFragment extends Fragment {

    private ConstraintLayout playerSheet;
    public static BottomSheetBehavior bottomSheetBehavior;
    private RecyclerView recyclerViewRecordings;
    private VoiceAdaptor recordingAdapter;
    private ArrayList<MyVoice> myVoiceArrayList;
    private CustomToolbarOption customToolbarOption;
    private FrameLayout allNoteToolBar;

    private MyVoice myChosenVoice;
    private ImageButton playerPlayBtn;
    private TextView fileNameTv , headerTitleTv;
    private SeekBar seekBar;
    private File[] files;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_audio_list, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init(view);
        fetchRecordings();
        addListener();
    }
    

    private void init(View v) {
        playerSheet = v.findViewById(R.id.player_sheet);
        bottomSheetBehavior = BottomSheetBehavior.from(playerSheet);
        setBottomSheet();
        customToolbarOption = v.findViewById(R.id.customToolbarOption);
        customToolbarOption.setVisibility(View.GONE);
        myVoiceArrayList = new ArrayList<>();
        playerPlayBtn = v.findViewById(R.id.player_play_btn);
        headerTitleTv = v.findViewById(R.id.player_header_title);
        fileNameTv = v.findViewById(R.id.textView3);
        seekBar = v.findViewById(R.id.seekBar);
        allNoteToolBar = v.findViewById(R.id.toolbar);
        allNoteToolBar.setEnabled(false);

        recyclerViewRecordings = v.findViewById(R.id.recyclerView);
        recyclerViewRecordings.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
        recyclerViewRecordings.setHasFixedSize(true);
    }

    private void fetchRecordings() {
        File root = android.os.Environment.getExternalStorageDirectory();
        String path = root.getAbsolutePath() + "/NotepadVoiceRecorder/Audios";
        Log.d("Files", "Path: " + path);
        File directory = new File(path);
        files = directory.listFiles();
        if (files != null) {
            for (int i = 0; i < files.length; i++) {
                String fileName = files[i].getName();
                String recordingUri = root.getAbsolutePath() + "/NotepadVoiceRecorder/Audios/" + fileName;
                MyVoice myVoice = new MyVoice(recordingUri, fileName, false , files[i].lastModified());
                myVoiceArrayList.add(myVoice);
            }
        }
        recordingAdapter = new VoiceAdaptor(getContext(), myVoiceArrayList , playerPlayBtn,fileNameTv , headerTitleTv , seekBar);
        recyclerViewRecordings.setAdapter(recordingAdapter);
    }

    private void setBottomSheet() {
        bottomSheetBehavior.addBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_HIDDEN) {//if it goes to the bottom of the screen
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);// in the first position that it used to be
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
    }

    private void addListener() {

        recordingAdapter.setOnVoiceMassageClickListener(new OnVoiceMassageClickListener() {

            @Override
            public void onItemLongClicked(MyVoice item) {
                customToolbarOption.setVisibility(View.VISIBLE);
                customToolbarOption.hideStar();
                myChosenVoice = item;
            }
        });

        //add listener to custom toolbar option and set being archived or not to be saved in database
        customToolbarOption.setCustomToolbarOptionListener(new CustomToolbarOptionListener() {
            @Override
            public void onStarClicked() {
            }

            @Override
            public void onDeleteClicked() {
                deleteClicked();
            }

            @Override
            public void onCloseClicked() {
                customToolbarOption.setVisibility(View.GONE);
            }
        });
    }

    private void deleteClicked() {
        AlertDialog.Builder alert = new AlertDialog.Builder(getContext());
        alert.setMessage("are you sure you wanna delete it ??? ");
        alert.setPositiveButton("yes", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                if (files!= null){
                    for (int j = 0 ; j < files.length ; j++){
                        if (files[j].getAbsolutePath().equals(myChosenVoice.getUri())){
                            files[j].delete();
                            myVoiceArrayList.remove(myChosenVoice);
                        }
                    }
                }

                customToolbarOption.setVisibility(View.GONE);
                recyclerViewRecordings.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
                recyclerViewRecordings.setHasFixedSize(true);
            }
        });
        alert.setNegativeButton("no", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.cancel();
            }
        });
        alert.show();
    }
}
