package com.bullhead.equalizer;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.media.audiofx.BassBoost;
import android.media.audiofx.Equalizer;
import android.media.audiofx.PresetReverb;
import android.os.Bundle;
import android.os.Vibrator;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.fragment.app.Fragment;

import com.db.chart.model.LineSet;
import com.google.firebase.analytics.FirebaseAnalytics;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * A simple {@link Fragment} subclass.
 */
public class EqualizerFragment extends Fragment implements AppToEqualizerInterface {

    public static final String ARG_AUDIO_SESSIOIN_ID = "audio_session_id";

    static int themeColor = Color.parseColor("#08E0FF");
    public static Equalizer mEqualizer;
    SwitchCompat equalizerSwitch;
    public static BassBoost bassBoost;
    //    LineChartView chart;
    public static PresetReverb presetReverb;

    short lowerEqualizerBandLevel = 0;
    short upperEqualizerBandLevel = 0 ;

    int y = 0;

    int seekBarValue = 0;
    int spinner = 0;
    ImageView spinnerDropDownIcon;
    LinearLayout mLinearLayout;

    public static SeekBar[] seekBarFinal = new SeekBar[5];

    public static AnalogController bassController, reverbController;

    Spinner presetSpinner;

    Context ctx;

    public EqualizerFragment() {
        // Required empty public constructor
    }

    public static LineSet dataset;
    Paint paint;
    public static float[] points;
    short numberOfFrequencyBands;
    private int audioSesionId;
    static boolean showBackButton = true;
    private Vibrator vibrator;
    private GestureDetector gestureDetector;
    Button mSave;
    private static ImageView mOff;
    private static ImageView mOn;
    RelativeLayout mRlType;
    public static ArrayList<String> mListType;
    public static TextView mTxtName;
    public static String nameTypeEffects = "Normal";
    public TextView mTxt1;
    public TextView mTxt2;
    public TextView mTxt3;
    public TextView mTxt4;
    public TextView mTxt5;
    private FirebaseAnalytics mFirebaseAnalytics = null;

    LinearLayout equalizerContainer;

    SharePreferenceUtilEqualizer sharePreferenceUtilEqualizer;

    public static EqualizerFragment newInstance(int audioSessionId) {

        Bundle args = new Bundle();
        args.putInt(ARG_AUDIO_SESSIOIN_ID, audioSessionId);

        EqualizerFragment fragment = new EqualizerFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onResume() {
        super.onResume();
//        sharePreferenceUtilEqualizer = new SharePreferenceUtilEqualizer(requireActivity());
//        if (!sharePreferenceUtilEqualizer.getBoolean("ControllerEffect", false)) {
//            mRlType.setEnabled(false);
//            mTxtName.setTextColor(Color.parseColor("#FF8E8E8E"));
//        } else {
//            mRlType.setEnabled(true);
//            mTxtName.setTextColor(Color.parseColor("#FFFFFF"));
//        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // Khởi tạo Firebase Analytics
        mFirebaseAnalytics = FirebaseAnalytics.getInstance(requireContext());

        Settings.isEditing = true;

        if (getArguments() != null && getArguments().containsKey(ARG_AUDIO_SESSIOIN_ID)) {
            audioSesionId = getArguments().getInt(ARG_AUDIO_SESSIOIN_ID);
        }

        if (Settings.equalizerModel == null) {
            Settings.equalizerModel = new EqualizerModel();
            Settings.equalizerModel.setReverbPreset(PresetReverb.PRESET_NONE);
            Settings.equalizerModel.setBassStrength((short) (1000 / 19));
        }

        try {
            mEqualizer = new Equalizer(0, audioSesionId);
            bassBoost = new BassBoost(0, audioSesionId);
            bassBoost.setEnabled(Settings.isEqualizerEnabled);
            /*BassBoost.Settings bassBoostSettingTemp = bassBoost.getProperties();
            BassBoost.Settings bassBoostSetting = new BassBoost.Settings(bassBoostSettingTemp.toString());
            bassBoostSetting.strength = Settings.equalizerModel.getBassStrength();
            bassBoost.setProperties(bassBoostSetting);*/
            bassBoost.setStrength(Settings.equalizerModel.getBassStrength());

            presetReverb = new PresetReverb(0, audioSesionId);
            presetReverb.setPreset(Settings.equalizerModel.getReverbPreset());
            try {
                if (presetReverb != null){
                    presetReverb.setEnabled(Settings.isEqualizerEnabled);
                }
            }catch (Exception ex){
                Log.d("nnn", "onClick: "+ex.toString());
            }

            mEqualizer.setEnabled(Settings.isEqualizerEnabled);

            if (Settings.presetPos == 0) {
                for (short bandIdx = 0; bandIdx < mEqualizer.getNumberOfBands(); bandIdx++) {
                    mEqualizer.setBandLevel(bandIdx, (short) Settings.seekbarpos[bandIdx]);
                }
            } else {
                mEqualizer.usePreset((short) Settings.presetPos);
            }
        }catch (UnsupportedOperationException uoe){
            Toast.makeText(ctx, "Error while initializing Equalizer", Toast.LENGTH_SHORT).show();
        }
        catch (RuntimeException ex){
            Toast.makeText(ctx, "Error while initializing Equalizer", Toast.LENGTH_SHORT).show();
        }

        vibrator = (Vibrator) requireActivity().getSystemService(Context.VIBRATOR_SERVICE);
        setUpViewModel();
    }

//    private void loadAdInterstitial() {
//        if (!FirebaseRemoteConfig.getInstance().getBoolean(Constants.inter_category)) {
//            return;
//        }
//        mInterstitialAd = AperoAd.getInstance().getInterstitialAds(requireContext(), BuildConfig.inter_category);
//    }


    private void setUpViewModel() {

    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        ctx = context;
    }

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_equalizer, container, false);
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mSave = view.findViewById(R.id.mSave);
        mOff = view.findViewById(R.id.mOff);
        mOn = view.findViewById(R.id.mOn);
        mRlType = view.findViewById(R.id.mRlType);
        mTxtName = view.findViewById(R.id.mTxtName);
        equalizerContainer = view.findViewById(R.id.equalizerContainer);
        mTxt1 = view.findViewById(R.id.mTxt1);
        mTxt2 = view.findViewById(R.id.mTxt2);
        mTxt3 = view.findViewById(R.id.mTxt3);
        mTxt4 = view.findViewById(R.id.mTxt4);
        mTxt5 = view.findViewById(R.id.mTxt5);

        mOff.setOnClickListener(new View.OnClickListener() {
            @SuppressLint("UseCompatLoadingForDrawables")
            @Override
            public void onClick(View view) {
                tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_turn_on_click","Bật adjust","turn_on");
                mOff.setVisibility(View.GONE);
                mOn.setVisibility(View.VISIBLE);
                mEqualizer.setEnabled(true);
                for (SeekBar seekBar : seekBarFinal) {
                    seekBar.setEnabled(true);
                }
                bassController.setShouldHandleTouch(true);
                reverbController.setShouldHandleTouch(true);
                bassBoost.setEnabled(true);
                try {
                    if (presetReverb != null){
                        presetReverb.setEnabled(true);
                    }
                }catch (Exception ex){
                    Log.d("nnn", "onClick: "+ex.toString());
                }
            }
        });

        mOn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_turn_off_click","Tắt adjust","turn_off");
                Toast.makeText(requireContext(),"Adjusting the bands is disabled.",Toast.LENGTH_LONG).show();
                mOff.setVisibility(View.VISIBLE);
                mOn.setVisibility(View.GONE);
                mEqualizer.setEnabled(false);
                for (SeekBar seekBar : seekBarFinal) {
                    seekBar.setEnabled(false);
                }
                bassController.setShouldHandleTouch(false);
                reverbController.setShouldHandleTouch(false);
                bassBoost.setEnabled(false);
                try {
                    if (presetReverb != null){
                        presetReverb.setEnabled(false);
                    }
                }catch (Exception ex){
                    Log.d("nnn", "onClick: "+ex.toString());
                }
            }
        });

        equalizerContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bassBoost != null){
                    if (!bassBoost.getEnabled()){
                        Toast.makeText(requireContext(),"Adjusting the bands is disabled.",Toast.LENGTH_LONG).show();
                    }
                } else {
                    Toast.makeText(requireContext(),"Bass boost not initialized",Toast.LENGTH_LONG).show();
                }
            }
        });

        mSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_equalizer_save_click","User click vào Save","equalizer_save");
                // Gọi phương thức trong module app để mở activity
                ((EqualizerToAppListener) Objects.requireNonNull(getActivity())).onOpenActivitySave();
            }
        });

        mRlType.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sharePreferenceUtilEqualizer = new SharePreferenceUtilEqualizer(requireActivity());
                if (!sharePreferenceUtilEqualizer.getBoolean("ControllerEffect", false)) {
                    Toast.makeText(requireContext(),"Adjusting the bands is disabled.",Toast.LENGTH_LONG).show();
                } else {
                    ((EqualizerToAppListener) Objects.requireNonNull(getActivity())).onOpenActivityEffects(mListType);
                }
            }
        });

        spinnerDropDownIcon = view.findViewById(R.id.spinner_dropdown_icon);
        spinnerDropDownIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presetSpinner.performClick();
            }
        });

        presetSpinner = view.findViewById(R.id.equalizer_preset_spinner);


//        chart   = view.findViewById(R.id.lineChart);
        paint = new Paint();
        dataset = new LineSet();

        bassController = view.findViewById(R.id.controllerBass);
        reverbController = view.findViewById(R.id.controller3D);

        bassController.setLabel(getResources().getString(R.string.bass));
        reverbController.setLabel(getResources().getString(R.string.stereo));

        bassController.circlePaint2.setColor(getResources().getColor(R.color.color_circlePaint));
        bassController.linePaint.setColor(getResources().getColor(R.color.color_linePaint));
        bassController.invalidate();
        reverbController.circlePaint2.setColor(getResources().getColor(R.color.color_circlePaint));
        bassController.linePaint.setColor(getResources().getColor(R.color.color_linePaint));
        reverbController.invalidate();

        if (!Settings.isEqualizerReloaded) {
            int x = 0;
            if (bassBoost != null) {
                try {
                    x = ((bassBoost.getRoundedStrength() * 19) / 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (presetReverb != null) {
                try {
                    y = (presetReverb.getPreset() * 19) / 6;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (x == 0) {
                bassController.setProgress(1);
            } else {
                bassController.setProgress(x);
            }

            if (y == 0) {
                reverbController.setProgress(1);
            } else {
                reverbController.setProgress(y);
            }
        } else {
            int x = ((Settings.bassStrength * 19) / 1000);
            y = (Settings.reverbPreset * 19) / 6;
            if (x == 0) {
                bassController.setProgress(1);
            } else {
                bassController.setProgress(x);
            }

            if (y == 0) {
                reverbController.setProgress(1);
            } else {
                reverbController.setProgress(y);
            }
        }

        bassController.setOnProgressChangedListener(new AnalogController.onProgressChangedListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onProgressChanged(int progress) {
                tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_equalizer_bass_boost_click","User điều chỉnh Bass","boost_click");

                Settings.bassStrength = (short) (((float) 1000 / 19) * (progress));
                try {
                    bassBoost.setStrength(Settings.bassStrength);
                    Settings.equalizerModel.setBassStrength(Settings.bassStrength);
                    vibrator.vibrate(100);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        reverbController.setOnProgressChangedListener(new AnalogController.onProgressChangedListener() {
            @SuppressLint("MissingPermission")
            @Override
            public void onProgressChanged(int progress) {
                tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_equalizer_bass_stereo_click","User điều chỉnh Stereo","stereo_click");
                Settings.reverbPreset = (short) ((progress * 6) / 19);
                try {
                    presetReverb.setPreset(Settings.reverbPreset);
                    Settings.equalizerModel.setReverbPreset(Settings.reverbPreset);
                    vibrator.vibrate(30);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                y = progress;
            }
        });

        mLinearLayout = view.findViewById(R.id.equalizerContainer);

        TextView equalizerHeading = new TextView(getContext());
        equalizerHeading.setText(R.string.eq);
        equalizerHeading.setTextSize(20);
        equalizerHeading.setGravity(Gravity.CENTER_HORIZONTAL);

        numberOfFrequencyBands = 5;

        points = new float[numberOfFrequencyBands];

        try {
            lowerEqualizerBandLevel = mEqualizer.getBandLevelRange()[0];
            upperEqualizerBandLevel = mEqualizer.getBandLevelRange()[1];
        }catch (Exception e){
            //Toast.makeText(ctx, e.getMessage(), Toast.LENGTH_LONG).show();
        }


        for (short i = 0; i < numberOfFrequencyBands; i++) {
            final short equalizerBandIndex = i;
            final TextView frequencyHeaderTextView = new TextView(getContext());
            frequencyHeaderTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            ));
            frequencyHeaderTextView.setGravity(Gravity.CENTER_HORIZONTAL);
            frequencyHeaderTextView.setTextColor(Color.parseColor("#FFFFFF"));
            try{
                frequencyHeaderTextView.setText((mEqualizer.getCenterFreq(equalizerBandIndex) / 1000) + "Hz");

            }catch (Exception e){

            }

            LinearLayout seekBarRowLayout = new LinearLayout(getContext());
            seekBarRowLayout.setOrientation(LinearLayout.VERTICAL);

            TextView lowerEqualizerBandLevelTextView = new TextView(getContext());
            lowerEqualizerBandLevelTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.MATCH_PARENT
            ));
            lowerEqualizerBandLevelTextView.setTextColor(Color.parseColor("#FFFFFF"));
            lowerEqualizerBandLevelTextView.setText((lowerEqualizerBandLevel / 100) + "dB");

            TextView upperEqualizerBandLevelTextView = new TextView(getContext());
            lowerEqualizerBandLevelTextView.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            ));
            upperEqualizerBandLevelTextView.setTextColor(Color.parseColor("#FFFFFF"));
            upperEqualizerBandLevelTextView.setText((upperEqualizerBandLevel / 100) + "dB");

            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
            );
            layoutParams.weight = 1;

            SeekBar seekBar = new SeekBar(getContext());
            TextView textView = new TextView(getContext());
            switch (i) {
                case 0:
                    seekBar = view.findViewById(R.id.seekBar1);
                    textView = view.findViewById(R.id.textView1);
                    break;
                case 1:
                    seekBar = view.findViewById(R.id.seekBar2);
                    textView = view.findViewById(R.id.textView2);
                    break;
                case 2:
                    seekBar = view.findViewById(R.id.seekBar3);
                    textView = view.findViewById(R.id.textView3);
                    break;
                case 3:
                    seekBar = view.findViewById(R.id.seekBar4);
                    textView = view.findViewById(R.id.textView4);
                    break;
                case 4:
                    seekBar = view.findViewById(R.id.seekBar5);
                    textView = view.findViewById(R.id.textView5);
                    break;
            }
            seekBarFinal[i] = seekBar;

            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                int progressChangedValue = 0;

                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    Log.d("qqq", "onProgressChanged: " + "ok");
                    progressChangedValue = progress;
                }

                public void onStartTrackingTouch(SeekBar seekBar) {
                    Log.d("qqq", "onStartTrackingTouch: " + "ok");
                }

                public void onStopTrackingTouch(SeekBar seekBar) {
                    Log.d("qqq", "onStopTrackingTouch: " + "ok");
                }
            });

//            seekBar.getProgressDrawable().setColorFilter(Color.parseColor(""), PorterDuff.Mode.LIGHTEN);

//            seekBar.getThumb().setColorFilter(new PorterDuffColorFilter(Color.parseColor("#E83565"), PorterDuff.Mode.SRC_IN));
            seekBar.setId(i);
//            seekBar.setLayoutParams(layoutParams);
            seekBar.setMax(upperEqualizerBandLevel - lowerEqualizerBandLevel);

            textView.setText(frequencyHeaderTextView.getText());
            textView.setTextColor(Color.WHITE);
            textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

            if (Settings.isEqualizerReloaded) {
                points[i] = Settings.seekbarpos[i] - lowerEqualizerBandLevel;
                dataset.addPoint(frequencyHeaderTextView.getText().toString(), points[i]);
                seekBar.setProgress(Settings.seekbarpos[i] - lowerEqualizerBandLevel);
            } else {
                points[i] = mEqualizer != null?(mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel):0;
                dataset.addPoint(frequencyHeaderTextView.getText().toString(), points[i]);
                seekBar.setProgress(mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel);
                Settings.seekbarpos[i] = mEqualizer.getBandLevel(equalizerBandIndex);
                Settings.isEqualizerReloaded = true;
            }
            switch (equalizerBandIndex){
                case 0: {
                    mTxt1.setText((seekBar.getProgress()/30)+"");
                    break;
                }
                case 1: {
                    mTxt2.setText((seekBar.getProgress()/30)+"");
                    break;
                }
                case 2: {
                    mTxt3.setText((seekBar.getProgress()/30)+"");
                    break;
                }
                case 3: {
                    mTxt4.setText((seekBar.getProgress()/30)+"");
                    break;
                }
                case 4: {
                    mTxt5.setText((seekBar.getProgress()/30)+"");
                    break;
                }
            }

            seekBar.setOnTouchListener(new View.OnTouchListener() {
                @SuppressLint("ClickableViewAccessibility")
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    if (event.getAction() == MotionEvent.ACTION_DOWN) {
                        if(bassBoost != null) {
                            if (!bassBoost.getEnabled()){
                                Toast.makeText(requireContext(),"Adjusting the bands is disabled.",Toast.LENGTH_LONG).show();
                                return true;
                            }
                        }else {
                            Toast.makeText(requireContext(),"Bass boost not initialized.",Toast.LENGTH_LONG).show();
                        }

                    }
                    return false;
                }
            });

            seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
                @Override
                public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                    try {
                        mEqualizer.setBandLevel(equalizerBandIndex, (short) (progress + lowerEqualizerBandLevel));
                        points[seekBar.getId()] = mEqualizer.getBandLevel(equalizerBandIndex) - lowerEqualizerBandLevel;
                        Settings.seekbarpos[seekBar.getId()] = (progress + lowerEqualizerBandLevel);
                        Settings.equalizerModel.getSeekbarpos()[seekBar.getId()] = (progress + lowerEqualizerBandLevel);
                        dataset.updateValues(points);
                        seekBarValue = progress + lowerEqualizerBandLevel;
                    }catch (Exception ex){
                        Log.d("nnn", "onProgressChanged: "+ex.toString());
                    }

                    SharedPreferences sharedPreferences = Objects.requireNonNull(getContext()).getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putInt("seekBarValue", seekBarValue);
                    editor.apply();

                    mTxtName.setText("Custome");
                    nameTypeEffects = "Custome";
                    tracKingFirebaseAnalytics(mFirebaseAnalytics,"home_equalizer_frequency_click","User điều chỉnh tần số","frequency_click");
                }

                @Override
                public void onStartTrackingTouch(SeekBar seekBar) {
                    presetSpinner.setSelection(0);
                    Settings.presetPos = 0;
                    Settings.equalizerModel.setPresetPos(0);
                }

                @Override
                public void onStopTrackingTouch(SeekBar seekBar) {

                }
            });
        }

        equalizeSound();

        paint.setColor(Color.parseColor("#555555"));
        paint.setStrokeWidth((float) (1.10 * Settings.ratio));

        dataset.setColor(themeColor);
        dataset.setSmooth(true);
        dataset.setThickness(5);

//        chart.setXAxis(false);
//        chart.setYAxis(false);

//        chart.setYLabels(AxisController.LabelPosition.NONE);
//        chart.setXLabels(AxisController.LabelPosition.NONE);
//        chart.setGrid(ChartView.GridType.NONE, 7, 10, paint);

//        chart.setAxisBorderValues(-300, 3300);

//        chart.addData(dataset);
//        chart.show();

        Button mEndButton = new Button(getContext());
        mEndButton.setBackgroundColor(themeColor);
        mEndButton.setTextColor(Color.WHITE);
    }

    public void equalizeSound() {
        ArrayList<String> equalizerPresetNames = new ArrayList<>();
        ArrayAdapter<String> equalizerPresetSpinnerAdapter = new ArrayAdapter<>(ctx,
                R.layout.spinner_item,
                equalizerPresetNames);
        equalizerPresetSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        if (mEqualizer != null){
            for (short i = 0; i < mEqualizer.getNumberOfPresets(); i++) {
                equalizerPresetNames.add(mEqualizer.getPresetName(i));
            }
            mListType = equalizerPresetNames;
        }

        presetSpinner.setAdapter(equalizerPresetSpinnerAdapter);
        //presetSpinner.setDropDownWidth((Settings.screen_width * 3) / 4);
        if (Settings.isEqualizerReloaded && Settings.presetPos != 0) {
//            correctPosition = false;
            presetSpinner.setSelection(Settings.presetPos);
        }

        presetSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateEqualizer(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

    }

    public void updateEqualizer(int position) {
        if (position >  0) {
            try {
                mEqualizer.usePreset((short) (position - 1));
            } catch (UnsupportedOperationException uoe){
                Log.e("111111", uoe.getMessage());
                //Toast.makeText(ctx, "Error while updating Equalizer", Toast.LENGTH_SHORT).show();
            }
            Settings.presetPos = position;
            short numberOfFreqBands = 5;

            final short lowerEqualizerBandLevel = (mEqualizer != null)? mEqualizer.getBandLevelRange()[0] : 0;

            for (short i = 0; i < numberOfFreqBands; i++) {
                seekBarFinal[i].setProgress((mEqualizer != null)? mEqualizer.getBandLevel(i) - lowerEqualizerBandLevel : 0);
                points[i] = mEqualizer.getBandLevel(i) - lowerEqualizerBandLevel;
                Settings.seekbarpos[i] = (mEqualizer != null)? mEqualizer.getBandLevel(i) : 0;
                Settings.equalizerModel.getSeekbarpos()[i] = (mEqualizer != null)? mEqualizer.getBandLevel(i) : 0;
            }
            dataset.updateValues(points);
//                        chart.notifyDataUpdate();
        }
        Settings.equalizerModel.setPresetPos(position);
    }

    public void setEqualizer(int seekBar) {
        seekBarFinal[0].setProgress(seekBar);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mEqualizer != null) {
            mEqualizer.release();
        }

        if (bassBoost != null) {
            bassBoost.release();
        }

        if (presetReverb != null) {
            presetReverb.release();
        }

        Settings.isEditing = false;
    }

    public static Builder newBuilder() {
        return new Builder();
    }

    @Override
    public void onUpdateMyType(int position, String name,int seekbar0, int seekbar1, int seekbar2, int seekbar3, int seekbar4) {
        try {
            seekBarFinal[0].setProgress(seekbar0-mEqualizer.getBandLevelRange()[0]);
            seekBarFinal[1].setProgress(seekbar1-mEqualizer.getBandLevelRange()[0]);
            seekBarFinal[2].setProgress(seekbar2-mEqualizer.getBandLevelRange()[0]);
            seekBarFinal[3].setProgress(seekbar3-mEqualizer.getBandLevelRange()[0]);
            seekBarFinal[4].setProgress(seekbar4-mEqualizer.getBandLevelRange()[0]);
            nameTypeEffects = name;
            mTxtName.setText(name);
        }catch (Exception ex){
            Log.d("nnn", "onUpdateMyType: "+ex.toString());
        }
    }

    @Override
    public void onUpdateType(int position, String name) {
        Log.d("qqq", "onUpdateType: " + position);
        updateEqualizer(position);
        nameTypeEffects = name;
        mTxtName.setText(name);
    }

    @Override
    public void setTypeEffects(int seekbar) {
        setEqualizer(seekbar);
    }

    @Override
    public void setOffEqualizer(boolean isCheck) {
        if (bassBoost != null){
            if (bassBoost.getEnabled()) {
                mOff.setVisibility(View.VISIBLE);
                mOn.setVisibility(View.GONE);
                mEqualizer.setEnabled(false);
                for (SeekBar seekBar : seekBarFinal) {
                    seekBar.setEnabled(false);
                }
                bassController.setShouldHandleTouch(false);
                reverbController.setShouldHandleTouch(false);
                bassBoost.setEnabled(false);
                try {
                    if (presetReverb != null){
                        presetReverb.setEnabled(false);
                    }
                }catch (Exception ex){
                    Log.d("nnn", "onClick: "+ex.toString());
                }
            } else {
                mOff.setVisibility(View.GONE);
                mOn.setVisibility(View.VISIBLE);
                mEqualizer.setEnabled(true);
                for (SeekBar seekBar : seekBarFinal) {
                    seekBar.setEnabled(true);
                }
                bassController.setShouldHandleTouch(true);
                reverbController.setShouldHandleTouch(true);
                bassBoost.setEnabled(true);
                try {
                    if (presetReverb != null){
                        presetReverb.setEnabled(true);
                    }
                }catch (Exception ex){
                    Log.d("nnn", "onClick: "+ex.toString());
                }
            }
        }

    }

    @Override
    public void setNameTypeEffects(String name) {
        mTxtName.setText(name);
        EqualizerFragment.nameTypeEffects = name;
    }

    public static class Builder {
        private int id = -1;

        public Builder setAudioSessionId(int id) {
            this.id = id;
            return this;
        }

        public Builder setAccentColor(int color) {
            themeColor = color;
            return this;
        }

        public Builder setShowBackButton(boolean show) {
            showBackButton = show;
            return this;
        }

        public EqualizerFragment build() {
            return EqualizerFragment.newInstance(id);
        }
    }


    public static Drawable setTint(Drawable d, int color) {
        Drawable wrappedDrawable = DrawableCompat.wrap(d);
        DrawableCompat.setTint(wrappedDrawable, color);
        return wrappedDrawable;
    }

    public Boolean checkOnOffSave() {
        List<Integer> progressList = new ArrayList<>();
        for (SeekBar seek : seekBarFinal) {
            int progress = seek.getProgress();
            progressList.add(progress);
        }
        final short lowerEqualizerBandLevel = mEqualizer.getBandLevelRange()[0];
        List<Integer> valueList = new ArrayList<>();
        for (int j = 0; j < 5; j++) {
            valueList.add(mEqualizer.getBandLevel((short) j) - lowerEqualizerBandLevel);
        }
        if (!progressList.equals(valueList)) {
            return true;
        } else {
            return false;
        }
    }

    public void tracKingFirebaseAnalytics(FirebaseAnalytics mFirebaseAnalytics,String event_name,String content,String name){
        Bundle params = new Bundle();
        params.putString(event_name, content);
        mFirebaseAnalytics.logEvent(name, params);
    }

}
