/* Copyright 2019 Thomas Schneider
 *
 * This file is a part of Fedilab
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 3 of the
 * License, or (at your option) any later version.
 *
 * Fedilab is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 * Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with Fedilab; if not,
 * see <http://www.gnu.org/licenses>. */
package app.fedilab.android.activities;

import android.app.NotificationManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.SwitchCompat;
import androidx.core.content.ContextCompat;

import app.fedilab.android.R;
import app.fedilab.android.client.Entities.Account;
import app.fedilab.android.helper.Helper;
import app.fedilab.android.jobs.ApplicationJob;
import app.fedilab.android.jobs.NotificationsSyncJob;
import app.fedilab.android.services.LiveNotificationDelayedService;
import app.fedilab.android.services.LiveNotificationService;
import app.fedilab.android.services.StopDelayedNotificationReceiver;
import app.fedilab.android.services.StopLiveNotificationReceiver;
import app.fedilab.android.sqlite.AccountDAO;
import app.fedilab.android.sqlite.Sqlite;
import es.dmoral.toasty.Toasty;

import static app.fedilab.android.helper.BaseHelper.startStreaming;

/**
 * Created by Thomas on 01/07/2019.
 * Settings activity
 */

public class SettingsActivity extends BaseActivity {


    public static boolean needRestart;
    protected int res;
    private int style;
    private int liveNotificationCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedPreferences sharedpreferences = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
        int theme = sharedpreferences.getInt(Helper.SET_THEME, Helper.THEME_DARK);
        switch (theme) {
            case Helper.THEME_LIGHT:
                setTheme(R.style.AppTheme);
                break;
            case Helper.THEME_BLACK:
                setTheme(R.style.AppThemeBlack);
                break;
            default:
                setTheme(R.style.AppThemeDark);
        }
        needRestart = false;
        if (getSupportActionBar() != null)
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
            assert inflater != null;
            View view = inflater.inflate(R.layout.simple_bar, new LinearLayout(SettingsActivity.this), false);
            view.setBackground(new ColorDrawable(ContextCompat.getColor(SettingsActivity.this, R.color.cyanea_primary)));
            actionBar.setCustomView(view, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
            ImageView toolbar_close = actionBar.getCustomView().findViewById(R.id.toolbar_close);
            TextView toolbar_title = actionBar.getCustomView().findViewById(R.id.toolbar_title);
            toolbar_close.setOnClickListener(v -> finish());
            toolbar_title.setText(R.string.settings);
        }
        setContentView(R.layout.activity_settings);

        if (theme == Helper.THEME_DARK) {
            style = R.style.DialogDark;
        } else if (theme == Helper.THEME_BLACK) {
            style = R.style.DialogBlack;
        } else {
            style = R.style.Dialog;
        }


        boolean display_content_after_fetch_more = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, true);
        final SwitchCompat set_display_content_after_fetch_more = findViewById(R.id.set_display_content_after_fetch_more);
        set_display_content_after_fetch_more.setChecked(display_content_after_fetch_more);
        set_display_content_after_fetch_more.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_DISPLAY_CONTENT_AFTER_FM, set_display_content_after_fetch_more.isChecked());
            editor.apply();
        });

        boolean notif_validation = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION, false);
        final SwitchCompat set_share_validation = findViewById(R.id.set_share_validation);
        set_share_validation.setChecked(notif_validation);

        set_share_validation.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_NOTIF_VALIDATION, set_share_validation.isChecked());
            editor.apply();
        });

        boolean notif_validation_fav = sharedpreferences.getBoolean(Helper.SET_NOTIF_VALIDATION_FAV, false);
        final SwitchCompat set_share_validation_fav = findViewById(R.id.set_share_validation_fav);
        set_share_validation_fav.setChecked(notif_validation_fav);

        set_share_validation_fav.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_NOTIF_VALIDATION_FAV, set_share_validation_fav.isChecked());
            editor.apply();
        });

        EditText set_invidious_host = findViewById(R.id.set_invidious_host);
        String invidiousHost = sharedpreferences.getString(Helper.SET_INVIDIOUS_HOST, null);
        if (invidiousHost != null) {
            set_invidious_host.setText(invidiousHost);
        }
        set_invidious_host.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) {
                SharedPreferences.Editor editor = sharedpreferences.edit();
                if (s.toString().trim().length() > 0) {
                    editor.putString(Helper.SET_INVIDIOUS_HOST, s.toString().toLowerCase().trim());
                } else {
                    editor.putString(Helper.SET_INVIDIOUS_HOST, null);
                }
                editor.apply();
            }
        });

        EditText set_nitter_host = findViewById(R.id.set_nitter_host);
        String nitterHost = sharedpreferences.getString(Helper.SET_NITTER_HOST, null);
        if (nitterHost != null) {
            set_nitter_host.setText(nitterHost);
        }
        set_nitter_host.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) {
                SharedPreferences.Editor editor = sharedpreferences.edit();
                if (s.toString().trim().length() > 0) {
                    editor.putString(Helper.SET_NITTER_HOST, s.toString().toLowerCase().trim());
                } else {
                    editor.putString(Helper.SET_NITTER_HOST, null);
                }
                editor.apply();
            }
        });


        TextView set_bibliogram_host = findViewById(R.id.set_bibliogram_host);

        String bibliogramHost = sharedpreferences.getString(Helper.SET_BIBLIOGRAM_HOST, null);
        if (bibliogramHost != null) {
            set_bibliogram_host.setText(bibliogramHost);
        }
        set_bibliogram_host.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) {
                SharedPreferences.Editor editor = sharedpreferences.edit();
                if (s.toString().trim().length() > 0) {
                    editor.putString(Helper.SET_BIBLIOGRAM_HOST, s.toString().toLowerCase().trim());
                } else {
                    editor.putString(Helper.SET_BIBLIOGRAM_HOST, null);
                }
                editor.apply();
            }
        });


        boolean expand_cw = sharedpreferences.getBoolean(Helper.SET_EXPAND_CW, false);
        final SwitchCompat set_expand_cw = findViewById(R.id.set_expand_cw);
        set_expand_cw.setChecked(expand_cw);

        set_expand_cw.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_EXPAND_CW, set_expand_cw.isChecked());
            editor.apply();
        });

        boolean expand_media = sharedpreferences.getBoolean(Helper.SET_EXPAND_MEDIA, false);
        final SwitchCompat set_expand_media = findViewById(R.id.set_expand_image);
        set_expand_media.setChecked(expand_media);

        set_expand_media.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_EXPAND_MEDIA, set_expand_media.isChecked());
            editor.apply();
        });


        int truncate_toots_size = sharedpreferences.getInt(Helper.SET_TRUNCATE_TOOTS_SIZE, 0);
        SeekBar set_truncate_size = findViewById(R.id.set_truncate_size);
        set_truncate_size.setMax(20);
        set_truncate_size.setProgress(truncate_toots_size);
        TextView set_truncate_toots = findViewById(R.id.set_truncate_toots);
        set_truncate_toots.setText(String.valueOf(truncate_toots_size));
        set_truncate_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                set_truncate_toots.setText(String.valueOf(progress));
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putInt(Helper.SET_TRUNCATE_TOOTS_SIZE, progress);
                editor.apply();
            }
        });

        boolean quick_reply = sharedpreferences.getBoolean(Helper.SET_QUICK_REPLY, true);
        final SwitchCompat set_quick_reply = findViewById(R.id.set_quick_reply);
        set_quick_reply.setChecked(quick_reply);

        set_quick_reply.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_QUICK_REPLY, set_quick_reply.isChecked());
            editor.apply();
        });

        boolean fit_preview = sharedpreferences.getBoolean(Helper.SET_FULL_PREVIEW, false);
        final SwitchCompat set_fit_preview = findViewById(R.id.set_fit_preview);
        set_fit_preview.setChecked(fit_preview);

        set_fit_preview.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_FULL_PREVIEW, set_fit_preview.isChecked());
            editor.apply();
        });


        boolean disableGif = sharedpreferences.getBoolean(Helper.SET_DISABLE_GIF, false);
        final SwitchCompat set_disable_gif = findViewById(R.id.set_disable_gif);
        set_disable_gif.setChecked(disableGif);
        set_disable_gif.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_DISABLE_GIF, set_disable_gif.isChecked());
            editor.apply();
            recreate();
        });


        boolean disableAnimatedEmoji = sharedpreferences.getBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, false);
        final SwitchCompat set_disable_animated_emoji = findViewById(R.id.set_disable_animated_emoji);
        set_disable_animated_emoji.setChecked(disableAnimatedEmoji);
        set_disable_animated_emoji.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_DISABLE_ANIMATED_EMOJI, set_disable_animated_emoji.isChecked());
            editor.apply();
        });

        boolean display_card = sharedpreferences.getBoolean(Helper.SET_DISPLAY_CARD, false);
        final SwitchCompat set_display_card = findViewById(R.id.set_display_card);
        set_display_card.setChecked(display_card);
        set_display_card.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_DISPLAY_CARD, set_display_card.isChecked());
            editor.apply();
        });

        boolean notify = sharedpreferences.getBoolean(Helper.SET_NOTIFY, true);
        final SwitchCompat switchCompatNotify = findViewById(R.id.set_notify);
        switchCompatNotify.setChecked(notify);

        switchCompatNotify.setOnCheckedChangeListener((buttonView, isChecked) -> {
            // Save the state here
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_NOTIFY, isChecked);
            editor.apply();
            if (isChecked) {
                startStreaming(SettingsActivity.this);
            } else {
                sendBroadcast(new Intent(getApplicationContext(), StopLiveNotificationReceiver.class));
                if (Build.VERSION.SDK_INT >= 26) {
                    NotificationManager notif = ((NotificationManager) getSystemService(NOTIFICATION_SERVICE));
                    if (notif != null) {
                        notif.deleteNotificationChannel(LiveNotificationDelayedService.CHANNEL_ID);
                    }
                }
            }
        });


        SQLiteDatabase db = Sqlite.getInstance(getApplicationContext(), Sqlite.DB_NAME, null, Sqlite.DB_VERSION).open();
        String userId = sharedpreferences.getString(Helper.PREF_KEY_ID, null);
        String instance = sharedpreferences.getString(Helper.PREF_INSTANCE, Helper.getLiveInstance(getApplicationContext()));
        final Account account = new AccountDAO(getApplicationContext(), db).getUniqAccount(userId, instance);
        boolean allow_live_notifications = sharedpreferences.getBoolean(Helper.SET_ALLOW_STREAM + userId + instance, true);
        TextView set_allow_live_notifications_title = findViewById(R.id.set_allow_live_notifications_title);
        set_allow_live_notifications_title.setText(getString(R.string.set_allow_live_notifications, account.getAcct() + "@" + account.getInstance()));
        final SwitchCompat set_allow_live_notifications = findViewById(R.id.set_allow_live_notifications);
        set_allow_live_notifications.setChecked(allow_live_notifications);
        set_allow_live_notifications.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_ALLOW_STREAM + userId + instance, set_allow_live_notifications.isChecked());
            editor.apply();
            if (set_allow_live_notifications.isChecked()) {
                LiveNotificationDelayedService.totalAccount++;
            } else {
                LiveNotificationDelayedService.totalAccount--;
            }
            if (set_allow_live_notifications.isChecked()) {
                LiveNotificationDelayedService.totalAccount++;
            } else {
                LiveNotificationDelayedService.totalAccount--;
            }
            startStreaming(SettingsActivity.this);

        });
        final ImageButton set_allow_live_notifications_others = findViewById(R.id.set_allow_live_notifications_others);
        set_allow_live_notifications_others.setOnClickListener(view -> {
            Intent intent = new Intent(SettingsActivity.this, LiveNotificationSettingsAccountsActivity.class);
            startActivity(intent);
        });

        //Live notification mode
        final Spinner set_live_type = findViewById(R.id.set_live_type);
        String[] labels = {getString(R.string.live_notif), getString(R.string.live_delayed), getString(R.string.no_live_notif)};
        ArrayAdapter<String> adapterLive = new ArrayAdapter<>(SettingsActivity.this,
                android.R.layout.simple_spinner_dropdown_item, labels);

        LinearLayout live_notif_per_account = findViewById(R.id.live_notif_per_account);
        set_live_type.setAdapter(adapterLive);
        if (Helper.liveNotifType(SettingsActivity.this) == Helper.NOTIF_NONE) {
            live_notif_per_account.setVisibility(View.GONE);
        }
        TextView set_live_type_indication = findViewById(R.id.set_live_type_indication);
        switch (Helper.liveNotifType(SettingsActivity.this)) {
            case Helper.NOTIF_LIVE:
                set_live_type_indication.setText(R.string.live_notif_indication);
                break;
            case Helper.NOTIF_DELAYED:
                set_live_type_indication.setText(R.string.set_live_type_indication);
                break;
            case Helper.NOTIF_NONE:
                set_live_type_indication.setText(R.string.no_live_indication);
                break;
        }
        set_live_type.setSelection(Helper.liveNotifType(SettingsActivity.this));
        liveNotificationCount = 0;
        set_live_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (liveNotificationCount > 0) {
                    SharedPreferences.Editor editor = sharedpreferences.edit();

                    sendBroadcast(new Intent(SettingsActivity.this, StopLiveNotificationReceiver.class));
                    sendBroadcast(new Intent(SettingsActivity.this, StopDelayedNotificationReceiver.class));
                    ApplicationJob.cancelAllJob(NotificationsSyncJob.NOTIFICATION_REFRESH);
                    switch (position) {
                        case Helper.NOTIF_LIVE:
                            editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, true);
                            editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false);
                            live_notif_per_account.setVisibility(View.VISIBLE);
                            editor.commit();
                            set_live_type_indication.setText(R.string.live_notif_indication);
                            Handler handler = new Handler();
                            handler.postDelayed(() -> {
                                startStreaming(SettingsActivity.this);
                            }, 1000);
                            break;
                        case Helper.NOTIF_DELAYED:
                            editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false);
                            editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, true);
                            live_notif_per_account.setVisibility(View.VISIBLE);
                            set_live_type_indication.setText(R.string.set_live_type_indication);
                            editor.commit();
                            handler = new Handler();
                            handler.postDelayed(() -> {
                                startStreaming(SettingsActivity.this);
                            }, 1000);
                            break;
                        case Helper.NOTIF_NONE:
                            editor.putBoolean(Helper.SET_LIVE_NOTIFICATIONS, false);
                            editor.putBoolean(Helper.SET_DELAYED_NOTIFICATIONS, false);
                            editor.commit();
                            set_live_type_indication.setText(R.string.no_live_indication);
                            live_notif_per_account.setVisibility(View.GONE);
                            NotificationsSyncJob.schedule(false);
                            break;
                    }
                } else {
                    liveNotificationCount++;
                }
            }

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

            }
        });

        boolean clear_cache_exit = sharedpreferences.getBoolean(Helper.SET_CLEAR_CACHE_EXIT, false);
        final SwitchCompat set_clear_cache_exit = findViewById(R.id.set_clear_cache_exit);
        set_clear_cache_exit.setChecked(clear_cache_exit);
        set_clear_cache_exit.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_CLEAR_CACHE_EXIT, set_clear_cache_exit.isChecked());
            editor.apply();
        });


        // NSFW Timeout
        SeekBar nsfwTimeoutSeekBar = findViewById(R.id.set_nsfw_timeout);
        final TextView set_nsfw_timeout_value = findViewById(R.id.set_nsfw_timeout_value);

        nsfwTimeoutSeekBar.setMax(30);

        int nsfwTimeout = sharedpreferences.getInt(Helper.SET_NSFW_TIMEOUT, 5);

        nsfwTimeoutSeekBar.setProgress(nsfwTimeout);
        set_nsfw_timeout_value.setText(String.valueOf(nsfwTimeout));

        nsfwTimeoutSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                set_nsfw_timeout_value.setText(String.valueOf(progress));

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putInt(Helper.SET_NSFW_TIMEOUT, progress);
                editor.apply();
            }
        });


        final ImageView set_toot_visibility = findViewById(R.id.set_toot_visibility);
        if (theme == Helper.THEME_DARK) {
            Helper.changeDrawableColor(getApplicationContext(), set_toot_visibility, R.color.dark_text);
        } else {
            Helper.changeDrawableColor(getApplicationContext(), set_toot_visibility, R.color.white);
        }
        //Only displayed for non locked accounts
        String defaultVisibility = account.isLocked() ? "private" : "public";
        String tootVisibility = sharedpreferences.getString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), defaultVisibility);
        switch (tootVisibility) {
            case "public":
                set_toot_visibility.setImageResource(R.drawable.ic_public);
                break;
            case "unlisted":
                set_toot_visibility.setImageResource(R.drawable.ic_lock_open);
                break;
            case "private":
                set_toot_visibility.setImageResource(R.drawable.ic_lock_outline);
                break;
            case "direct":
                set_toot_visibility.setImageResource(R.drawable.ic_mail_outline);
                break;
        }

        set_toot_visibility.setOnClickListener(v -> {
            final SharedPreferences sharedpreferences1 = getSharedPreferences(Helper.APP_PREFS, MODE_PRIVATE);
            if (theme == Helper.THEME_DARK) {
                style = R.style.DialogDark;
            } else if (theme == Helper.THEME_BLACK) {
                style = R.style.DialogBlack;
            } else {
                style = R.style.Dialog;
            }
            AlertDialog.Builder dialog = new AlertDialog.Builder(SettingsActivity.this, style);
            dialog.setTitle(R.string.toot_visibility_tilte);
            final String[] stringArray = getResources().getStringArray(R.array.toot_visibility);
            final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, stringArray);
            dialog.setNegativeButton(R.string.cancel, (dialog12, position) -> dialog12.dismiss());

            dialog.setAdapter(arrayAdapter, (dialog1, position) -> {
                String visibility = "public";

                switch (position) {
                    case 0:
                        visibility = "public";
                        set_toot_visibility.setImageResource(R.drawable.ic_public);
                        break;
                    case 1:
                        visibility = "unlisted";
                        set_toot_visibility.setImageResource(R.drawable.ic_lock_open);
                        break;
                    case 2:
                        visibility = "private";
                        set_toot_visibility.setImageResource(R.drawable.ic_lock_outline);
                        break;
                    case 3:
                        visibility = "direct";
                        set_toot_visibility.setImageResource(R.drawable.ic_mail_outline);
                        break;
                }
                SharedPreferences.Editor editor = sharedpreferences1.edit();
                editor.putString(Helper.SET_TOOT_VISIBILITY + "@" + account.getAcct() + "@" + account.getInstance(), visibility);
                editor.apply();
                Toasty.info(getApplicationContext(), getString(R.string.toast_visibility_changed, "@" + account.getAcct() + "@" + account.getInstance()), Toast.LENGTH_SHORT).show();

                dialog1.dismiss();
            });
            dialog.show();
        });

        int split_size_val = sharedpreferences.getInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, Helper.SPLIT_TOOT_SIZE);

        LinearLayout set_split_container = findViewById(R.id.set_split_container);
        //split size
        SeekBar split_size = findViewById(R.id.set_split_size);
        final EditText split_text = findViewById(R.id.set_split_text);

        split_size.setProgress(0);
        split_text.setText(String.valueOf(split_size_val));
        split_text.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) { }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence != null && charSequence.length() > 0) {
                    int newValue = Integer.parseInt(charSequence.toString());
                    if (newValue > 0) {
                        SharedPreferences.Editor editor = sharedpreferences.edit();
                        editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, newValue);
                        editor.apply();
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        split_size.setMax(5);
        split_size.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                int newProgress = (progress + 1) * Helper.SPLIT_TOOT_SIZE;
                split_text.setText(String.valueOf(newProgress));
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putInt(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS_SIZE + userId + instance, newProgress);
                editor.apply();
            }
        });

        boolean split_toot = sharedpreferences.getBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, false);
        if (!split_toot) {
            set_split_container.setVisibility(View.GONE);
        }
        final SwitchCompat set_split_toot = findViewById(R.id.set_automatically_split_toot);
        set_split_toot.setChecked(split_toot);
        set_split_toot.setOnClickListener(v -> {
            SharedPreferences.Editor editor = sharedpreferences.edit();
            editor.putBoolean(Helper.SET_AUTOMATICALLY_SPLIT_TOOTS + userId + instance, set_split_toot.isChecked());
            editor.apply();
            if (set_split_toot.isChecked()) {
                set_split_container.setVisibility(View.VISIBLE);
            } else {
                set_split_container.setVisibility(View.GONE);
            }
        });

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

}
