public class FloatingActivity extends AppCompatActivity {
    static final String TAG = "FloatingActivity";
    private final Handler handler = new Handler();
    public Activity mActivity;
    MediaPlayer mediaPlayer;
    AppSharedPref appSharedPref;

    SaudSpinner to_custom_spinner, from_custom_spinner;
    AllLanguagesRepo languagesRepo;
    boolean isOpentranslateActivity = false;
    private EditText text;
    private String source_text = "";
    private String target_text = "";
    private String to_language_code;
    private String from_language_code;
    private MaterialButton btn_translate;
    private ProgressBar progress;
    private TextView translated_text;
    private String speak_code;
    private ImageView del_img;
    private ImageView from_speeker;
    private ImageView to_speeker;
    private ImageView more_img;
    private String final_string_for_speaking;
    private PopupWindow mPopupWindow;

    @SuppressLint("NonConstantResourceId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Thread.setDefaultUncaughtExceptionHandler(new CrashHandlerAC(new WeakReference<>(this)));
        languagesRepo = new AllLanguagesList().getAllLanguagesRepo(this);
        try {
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            getWindow().requestFeature(Window.FEATURE_NO_TITLE);
            getWindow().setBackgroundDrawableResource(R.color.realTranslucent);
            appSharedPref = AppSharedPref.newInstance(FloatingActivity.this);

            try {
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);
            } catch (Exception e) {
                new customException(TAG + " onCreate " + e.getMessage()).printStackTrace();
            }
        } catch (Exception e) {
            new customException(TAG + " onCreate " + e.getMessage()).printStackTrace();
        }

        setContentView(R.layout.activity_floating);

        ((CustomNativeBannerAdHolder) findViewById(R.id.nativeBanner))
                .loadBannerAd(
                        ConstantVal.FloatingNativeBannerAd
                        , null,
                        true
                );
        //AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);
        mActivity = this;
        progress = findViewById(R.id.progress);
        btn_translate = findViewById(R.id.btn_translate);
        translated_text = findViewById(R.id.translated_text);
        //toSpinner = (NiceSpinner) findViewById(R.id.to_spinner);
        from_speeker = findViewById(R.id.from_speeker);
        to_speeker = findViewById(R.id.to_speaker);
        more_img = findViewById(R.id.more_img);
        to_speeker.setTag("speak");
        from_speeker.setTag("speak");
        text = findViewById(R.id.text);
        del_img = findViewById(R.id.del_img);
        ImageView close = findViewById(R.id.close);
        TextView titleTextView = findViewById(R.id.titleTextView);
        RelativeLayout baseLayout = findViewById(R.id.base_popup_layout);
        to_custom_spinner = findViewById(R.id.to_custom_spinner);
        from_custom_spinner = findViewById(R.id.from_custom_spinner);
        to_custom_spinner.setText(appSharedPref.getToFloatingLang());
        from_custom_spinner.setText(appSharedPref.getFromFloatingLang());

        spinner_2_selection(appSharedPref.getToFloatingLang());
        spinner_1_selection(appSharedPref.getFromFloatingLang());

        text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() > 0) {
                    del_img.setVisibility(View.VISIBLE);
                } else {
                    del_img.setVisibility(View.INVISIBLE);
                }
            }
        });

        baseLayout.setOnClickListener(v -> {

        });
        close.setOnClickListener(v -> {
            finishAfterTransition();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
                Intent intent = new Intent(getApplicationContext(), ChildBubbleService.class);
                startService(intent);
            }
        });
        from_custom_spinner.setOnClickListener(v -> {
            try {
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                @SuppressLint("InflateParams") View customView = inflater.inflate(R.layout.custom_spinner2,
                        null);
                //int screen_width=getResources().getDisplayMetrics().widthPixels;
                int screen_height = getResources().getDisplayMetrics().heightPixels / 2;
                mPopupWindow = new PopupWindow(
                        customView,
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        screen_height,
                        true
                );
                mPopupWindow.setElevation(4.50f);
                mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                ListView listView = customView.findViewById(R.id.listView);

                listView.setOnItemClickListener((parent, view, position, id) -> {
                    try {
                        String s = listView.getItemAtPosition(position).toString();
                        try {
                            Thread.sleep(160);
                            mPopupWindow.dismiss();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        from_custom_spinner.setText(s);
                        source_text = s;
                        spinner_1_selection(source_text);
                        btn_translate.callOnClick();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });
                mPopupWindow.setAnimationStyle(R.style.animation_window);
                mPopupWindow.showAsDropDown(v);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        to_custom_spinner.setOnClickListener(v -> {
            try {
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                @SuppressLint("InflateParams") View customView = inflater.inflate(R.layout.custom_spinner, null);
                //int screen_width=getResources().getDisplayMetrics().widthPixels;
                int screen_height = getResources().getDisplayMetrics().heightPixels / 2;
                mPopupWindow = new PopupWindow(
                        customView,
                        WindowManager.LayoutParams.WRAP_CONTENT,
                        screen_height,
                        true
                );
                mPopupWindow.setElevation(4.50f);
                mPopupWindow.setBackgroundDrawable(new ColorDrawable(Color.WHITE));
                ListView listView = customView.findViewById(R.id.listView);
                listView.setOnItemClickListener((parent, view, position, id) -> {
                    try {
                        String s = listView.getItemAtPosition(position).toString();
                        try {
                            Thread.sleep(160);

                            mPopupWindow.dismiss();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        to_custom_spinner.setText(s);
                        target_text = s;
                        spinner_2_selection(target_text);
                        btn_translate.callOnClick();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });
                mPopupWindow.setAnimationStyle(R.style.animation_window);
                mPopupWindow.showAsDropDown(v);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        more_img.setOnClickListener(v -> {
            try {
                PopupMenu popupMenu = new PopupMenu(FloatingActivity.this, more_img);
                popupMenu.getMenuInflater()
                        .inflate(R.menu.main_menu, popupMenu.getMenu());
                //registering popup with OnMenuItemClickListener
                popupMenu.setOnMenuItemClickListener(item -> {
                    switch (item.getItemId()) {
                        case R.id.copy:
                            copy(translated_text.getText().toString());
                            break;
                        case R.id.share:
                            IntentUtils.share_text(FloatingActivity.this, translated_text.getText().toString());

                            break;
                    }
                    return true;
                });

                popupMenu.show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });

        from_speeker.setOnClickListener(v -> {
            try {
                if (AppUtills.getInstance().isNetworkAvailable(FloatingActivity.this)) {
                    if (!TextUtils.isEmpty(text.getText())) {
                        if (!speak_code.equals("speak")) {
                            final_string_for_speaking = null;

                            if ("speak".equals(from_speeker.getTag())) {
                                if (text.getText().toString().length() > 154) {
                                    String text1 = text.getText().toString().substring(0, 154);
                                    final_string_for_speaking = text.getText().toString().substring(155);
                                    prepare_for_speak(text1, to_language_code);
                                } else {
                                    prepare_for_speak(text.getText().toString(), to_language_code);
                                }
                                from_speeker.setImageResource(com.english.speakwidget.R.drawable.ic_stop_custom_iv);
                                from_speeker.setTag("stop");
                            } else if ("stop".equals(from_speeker.getTag())) {
                                mediaPlayer.reset();
                                from_speeker.setTag("speak");
                                from_speeker.setImageResource(R.drawable.ic_speaker);

                            }
                        } else {
                            if (mActivity != null)
                                Toast.makeText(mActivity, "Sorry currently this is not supported for voice output..", Toast.LENGTH_SHORT).show();
                        }

                    } else {
                        if (mActivity != null)
                            Toast.makeText(mActivity, "Enter text first..", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (mActivity != null)
                        Toast.makeText(mActivity, "Need working internet connection..", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        to_speeker.setOnClickListener(v -> {
            try {
                boolean chk = SpeakNotSupportedLang.newInstance()
                        .isSpeakSupported(to_custom_spinner.getText().toString());

                if (!chk) {
                    if (mActivity != null)
                        Toast.makeText(mActivity, "Sorry this language is not supported yet.", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (AppUtills.getInstance().isNetworkAvailable(FloatingActivity.this)) {
                    if (!TextUtils.isEmpty(translated_text.getText())) {
                        if (speak_code != null && !speak_code.equals("speak")) {
                            final_string_for_speaking = null;
                            if ("speak".equals(to_speeker.getTag())) {
                                if (translated_text.getText().toString().length() > 154) {
                                    String text = translated_text.getText().toString().substring(0, 154);
                                    final_string_for_speaking = translated_text.getText().toString().substring(155);
                                    prepare_for_speak(text, to_language_code);
                                } else {
                                    prepare_for_speak(translated_text.getText().toString(), to_language_code);
                                }
                                to_speeker.setImageResource(com.english.speakwidget.R.drawable.ic_stop_custom_iv);
                                to_speeker.setTag("stop");

                            } else if ("stop".equals(to_speeker.getTag())) {
                                mediaPlayer.reset();
                                to_speeker.setTag("speak");
                                to_speeker.setImageResource(R.drawable.ic_speaker);
                            }
                        } else {
                            if (mActivity != null)
                                Toast.makeText(mActivity, "Sorry currently this is not supported for voice output..", Toast.LENGTH_SHORT).show();
                        }
                    } else {
                        if (mActivity != null)
                            Toast.makeText(mActivity, "Translate text first..", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (mActivity != null)
                        Toast.makeText(mActivity, "Need working internet connection..", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        del_img.setOnClickListener(v -> {
            try {

                text.setText("");
                translated_text.setText("");
                if (mediaPlayer != null) {
                    mediaPlayer.reset();
                    to_speeker.setImageResource(R.drawable.ic_speaker);
                    to_speeker.setTag("speak");
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        from_language_code = "auto";
        titleTextView.setOnClickListener(v -> {
            try {
                isOpentranslateActivity = true;
                Intent intent = new Intent(FloatingActivity.this, MainActivity.class);
                if (!text.getText().toString().isEmpty()) {
                    StaticVariables.translatedText = translated_text.getText().toString();
                    StaticVariables.input_text = text.getText().toString();
                    StaticVariables.openingFromFloating = true;

                    StaticVariables.source_lang = from_custom_spinner.getText().toString();
                    StaticVariables.target_lang = to_custom_spinner.getText().toString();
//                    intent.putExtra("input_text", text.getText().toString());
//                    intent.putExtra("translated_text", translated_text.getText().toString());
                }
//                intent.putExtra("intent_from_floating", true);
                startActivity(intent);
                overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

                finishAfterTransition();
            } catch (Exception e) {
                e.printStackTrace();
            }

        });


        btn_translate.setOnClickListener(v -> {

            del_img.setEnabled(false);

            try {
                if (AppUtills.getInstance().isNetworkAvailable(mActivity)) {

                    String translation = new SqliteHelper(mActivity).getPreviousTranslatedText(
                            text.getText().toString(),
                            from_custom_spinner.getText().toString(),
                            to_custom_spinner.getText().toString()
                    );
                    translated_text.setText(translation);
                    boolean isTranslated = new SqliteHelper(mActivity).isTextAlreadyTranslated(
                            text.getText().toString(),
                            translated_text.getText().toString(),
                            from_custom_spinner.getText().toString(),
                            to_custom_spinner.getText().toString()
                    );
                    if (isTranslated) {
                        del_img.setEnabled(true);
                        return;
                    }
                    if (!text.getText().toString().trim().isEmpty()) {
                        if (mediaPlayer.isPlaying()) {
                            mediaPlayer.stop();
                            try {
                                to_speeker.setImageResource(R.drawable.ic_speaker);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            to_speeker.setTag("speak");
                        }
                        progress.setVisibility(View.VISIBLE);
                        btn_translate.setVisibility(View.GONE);
                        VolleyRequestHelper volleyRequestHelper = new VolleyRequestHelper();
                        volleyRequestHelper.makeTranslationRequest(getApplicationContext(), "auto", to_language_code, text.getText().toString().trim(), new VolleyRequestHelper.OnTranslationListener() {
                            @Override
                            public void onTranslate(translation_result_model translationModel) {

                                new Handler().postDelayed(() -> del_img.setEnabled(true),1000);

                                try {
                                    translated_text.setText(AppUtills.getInstance().CapitalizeFirstLetter(translationModel.getTranslatedText()));
                                    progress.setVisibility(View.GONE);
                                    btn_translate.setVisibility(View.VISIBLE);
                                    SqliteHelper helper = new SqliteHelper(mActivity);
                                    history_model h = new history_model();
                                    h.setSource_language_text(languagesRepo.getLanguageByLangCode(translationModel.getSourceLang()).getLangName());
                                    h.setTarget_language_text(to_custom_spinner.getText().toString());
                                    h.setSource_text(text.getText().toString().trim());
                                    h.setTarget_text(translationModel.getTranslatedText());
                                    h.setDate(getCurrentDate());
                                    helper.insert(h);

                                    selectSourceLanguage(translationModel.getSourceLang());



                                } catch (Exception e) {

                                    Log.d(FloatingActivity.class.getName(), " setOnTranslationListener " + e.getMessage());
                                }
                            }

                            @Override
                            public void onTranslateError(String error) {
                                try {
                                    progress.setVisibility(View.GONE);
                                    btn_translate.setVisibility(View.VISIBLE);

                                    del_img.setEnabled(true);

                                } catch (Exception e) {
                                    Log.d(FloatingActivity.class.getName(), " " + e.getMessage());
                                }
                            }
                        });

                    } else {
                        if (mActivity != null)
                            Toast.makeText(mActivity, "No text available", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    if (mActivity != null)
                        Toast.makeText(mActivity, "Internet is not available", Toast.LENGTH_SHORT).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        enableOrDisableMoreBtn();
        mediaPlayer = new MediaPlayer();
        new Handler(Looper.getMainLooper()).postDelayed(() -> paste(), 300);

        Rect rectangle = new Rect();
        Window window = getWindow();
        window.getDecorView().getWindowVisibleDisplayFrame(rectangle);

        window.findViewById(Window.ID_ANDROID_CONTENT).setOnClickListener(v -> {

        });
    }

    private String getCurrentDate() {
        Date c = Calendar.getInstance().getTime();
        SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy", Locale.getDefault());
        return df.format(c);
    }

    @Override
    public void onBackPressed() {
        finishAfterTransition();
    }

    private void enableOrDisableMoreBtn() {
        try {
            if (translated_text.getText().toString().isEmpty()) {
                more_img.setEnabled(false);
                more_img.setImageResource(R.drawable.ic_more);
            }
            TextWatcher textWatcher = new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                }

                @Override
                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }

                @Override
                public void afterTextChanged(Editable s) {
                    if (s.toString().isEmpty()) {
                        more_img.setEnabled(false);
                        more_img.setImageResource(R.drawable.ic_more);
                    } else {
                        more_img.setEnabled(true);
                        more_img.setImageResource(R.drawable.ic_more);
                    }

                }
            };
            translated_text.addTextChangedListener(textWatcher);

        } catch (Exception e) {
            new customException("ignore " + e.getMessage()).printStackTrace();
        }
    }

    private void paste() {
        try {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            if (clipboard != null && clipboard.hasPrimaryClip() && clipboard.getPrimaryClip() != null) {
                CharSequence clip = clipboard.getPrimaryClip().getItemAt(0).coerceToText(FloatingActivity.this).toString();
                text.setText(AppUtills.getInstance().CapitalizeFirstLetter(clip.toString().trim()));
                from_language_code = "auto";
                btn_translate.callOnClick();

            }
        } catch (Exception e) {
            new customException("ignore " + e.getMessage()).printStackTrace();
        }
    }