package com.atr.tedit.settings;

import android.app.Activity;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
//import android.support.constraint.ConstraintLayout;
import androidx.constraintlayout.widget.ConstraintLayout;
//import android.support.constraint.ConstraintSet;
import androidx.constraintlayout.widget.ConstraintSet;
//import android.support.v7.view.ContextThemeWrapper;
import androidx.appcompat.view.ContextThemeWrapper;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.HorizontalScrollView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewAnimator;

import com.atr.tedit.R;
import com.atr.tedit.TEditActivity;
import com.atr.tedit.dialog.ErrorMessage;
import com.atr.tedit.dialog.HelpDialog;
import com.atr.tedit.dialog.Sidebar;
import com.atr.tedit.file.AndPath;
import com.atr.tedit.mainstate.Browser;
import com.atr.tedit.mainstate.Editor;
import com.atr.tedit.settings.dialog.DirectoryPicker;
import com.atr.tedit.settings.dialog.TypefacePicker;
import com.atr.tedit.util.FontUtil;
import com.atr.tedit.util.SettingsApplicable;

/**
 * @author Adam T. Ryder
 * <a href="https://www.inventati.org/1337gallery">https://www.inventati.org/1337gallery</a>
 */

public class SettingsWindow extends Sidebar {
    private final long panelAnimLength;

    private final ViewAnimator settingsAnimator;

    private TempSettings tempSettings;
    private TempSettings localTempSettings;

    public SettingsWindow(TEditActivity context) {
        super(context, Sidebar.DIR_TO_LEFT, R.layout.settings_global, R.id.settingsRoot);

        final int fontSize = 16;
        final int colorCream = ctx.getThemeColor(R.color.cream);

        settingsAnimator = (ViewAnimator)sidebar;
        settingsAnimator.setInAnimation(AnimationUtils.loadAnimation(ctx, R.anim.settings_in));
        settingsAnimator.setOutAnimation(AnimationUtils.loadAnimation(ctx, R.anim.settings_out));
        panelAnimLength = settingsAnimator.getInAnimation().getDuration();

        int colorLightRust = ctx.getThemeColor(R.color.lightRust);

        Button saveButton = container.findViewById(R.id.saveButton);
        Button cancelButton = container.findViewById(R.id.cancelButton);

        ConstraintLayout csLayout = (ConstraintLayout)saveButton.getParent();
        ConstraintSet cset = new ConstraintSet();
        cset.clone(csLayout);

        csLayout.removeView(saveButton);
        saveButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        saveButton.setId(R.id.saveButton);
        saveButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        saveButton.setText(ctx.getText(R.string.save));
        saveButton.setTextColor(colorLightRust);
        csLayout.addView(saveButton);

        csLayout.removeView(cancelButton);
        cancelButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        cancelButton.setId(R.id.cancelButton);
        cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        cancelButton.setText(ctx.getText(R.string.cancel));
        cancelButton.setTextColor(colorLightRust);
        csLayout.addView(cancelButton);

        cset.applyTo(csLayout);

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                applySettings();
                close(true);
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                close(true);
            }
        });

        saveButton = container.findViewById(R.id.localSaveButton);
        cancelButton = container.findViewById(R.id.localCancelButton);

        csLayout = (ConstraintLayout)saveButton.getParent();
        cset = new ConstraintSet();
        cset.clone(csLayout);

        csLayout.removeView(saveButton);
        saveButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        saveButton.setId(R.id.localSaveButton);
        saveButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        saveButton.setText(ctx.getText(R.string.save));
        saveButton.setTextColor(colorLightRust);
        csLayout.addView(saveButton);

        csLayout.removeView(cancelButton);
        cancelButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        cancelButton.setId(R.id.localCancelButton);
        cancelButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        cancelButton.setText(ctx.getText(R.string.cancel));
        cancelButton.setTextColor(colorLightRust);
        csLayout.addView(cancelButton);

        cset.applyTo(csLayout);

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                applySettings();
                close(true);
            }
        });
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                close(true);
            }
        });

        Button localButton = container.findViewById(R.id.localButton);
        Button globalHelpButton = container.findViewById(R.id.helpButton);

        csLayout = (ConstraintLayout)localButton.getParent();
        cset = new ConstraintSet();
        cset.clone(csLayout);

        csLayout.removeView(localButton);
        localButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        localButton.setId(R.id.localButton);
        localButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        localButton.setText(ctx.getText(R.string.settings_local_button));
        localButton.setTextColor(colorLightRust);
        csLayout.addView(localButton);

        csLayout.removeView(globalHelpButton);
        globalHelpButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        globalHelpButton.setId(R.id.helpButton);
        globalHelpButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        globalHelpButton.setText(ctx.getText(R.string.help));
        globalHelpButton.setTextColor(colorLightRust);
        csLayout.addView(globalHelpButton);

        cset.applyTo(csLayout);

        Button globalButton = container.findViewById(R.id.globalButton);
        Button localHelpButton = container.findViewById(R.id.localHelpButton);

        csLayout = (ConstraintLayout)globalButton.getParent();
        cset = new ConstraintSet();
        cset.clone(csLayout);

        csLayout.removeView(globalButton);
        globalButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        globalButton.setId(R.id.globalButton);
        globalButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        globalButton.setText(ctx.getText(R.string.settings_global_button));
        globalButton.setTextColor(colorLightRust);
        csLayout.addView(globalButton);

        csLayout.removeView(localHelpButton);
        localHelpButton = new Button(new ContextThemeWrapper(ctx, R.style.buttonFlatDarkRust));
        localHelpButton.setId(R.id.localHelpButton);
        localHelpButton.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize);
        localHelpButton.setText(ctx.getText(R.string.help));
        localHelpButton.setTextColor(colorLightRust);
        csLayout.addView(localHelpButton);

        cset.applyTo(csLayout);

        localButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                settingsAnimator.getInAnimation().setDuration(panelAnimLength);
                settingsAnimator.getOutAnimation().setDuration(panelAnimLength);
                settingsAnimator.showNext();
            }
        });
        globalButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                settingsAnimator.getInAnimation().setDuration(panelAnimLength);
                settingsAnimator.getOutAnimation().setDuration(panelAnimLength);
                settingsAnimator.showPrevious();
            }
        });

        localHelpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int helpLayout = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
                        ? R.layout.help_settings_local : R.layout.help_settings_local_prelollipop;
                HelpDialog hd = HelpDialog.newInstance(helpLayout, ctx.getString(R.string.settings_local_button));
                hd.show(ctx.getSupportFragmentManager(), "HelpDialog");
            }
        });
        globalHelpButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int helpLayout;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
                    helpLayout = R.layout.help_settings_global;
                } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                    helpLayout = R.layout.help_settings_global_prepie;
                } else
                    helpLayout = R.layout.help_settings_global_prelollipop;
                HelpDialog hd = HelpDialog.newInstance(helpLayout, ctx.getString(R.string.settings_global_button));
                hd.show(ctx.getSupportFragmentManager(), "HelpDialog");
            }
        });

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            TextView pathView = container.findViewById(R.id.startupDir);
            pathView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
            pathView.setTextDirection((Settings.getSystemTextDirection() == Settings.TEXTDIR_LTR) ?
                    View.TEXT_DIRECTION_LTR : View.TEXT_DIRECTION_RTL);
        }

        Button startupDirButton = container.findViewById(R.id.startupBrowse);
        startupDirButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AndPath currentPath = tempSettings.startupDir;
                if (currentPath != null && !currentPath.getCurrent().exists()) {
                    while(currentPath.moveToParent() != null && !currentPath.getCurrent().exists())
                        continue;

                    if (!currentPath.getCurrent().exists()) {
                        currentPath = null;
                    }
                }

                if (currentPath == null && (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)) {
                    ErrorMessage em = ErrorMessage.getInstance(ctx.getString(R.string.alert),
                            ctx.getString(R.string.missing_dir));
                    em.show(ctx.getSupportFragmentManager(), "dialog");
                    return;
                }

                DirectoryPicker dialog = DirectoryPicker.newInstance(currentPath);
                dialog.show(ctx.getSupportFragmentManager(), DirectoryPicker.TAG);
            }
        });

        Button clearHistoryButton = container.findViewById(R.id.clearHistory);
        clearHistoryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (Settings.isSaveHistory()) {
                    Settings.clearHistory(ctx);
                    Toast.makeText(ctx, ctx.getString(R.string.alert_historyCleared), Toast.LENGTH_SHORT).show();
                    if (ctx.getFrag() instanceof Browser && ((Browser)ctx.getFrag()).isBrowsingPermittedDirs())
                        ((Browser)ctx.getFrag()).populatePermittedDirectories();
                } else
                    Toast.makeText(ctx, ctx.getString(R.string.alert_historyDisabled), Toast.LENGTH_SHORT).show();
            }
        });

        Button typefaceButton = container.findViewById(R.id.fontBrowse);
        Button editorTypefaceButton = container.findViewById(R.id.editorFontBrowse);
        Button localTypefaceButton = container.findViewById(R.id.localFontBrowse);
        typefaceButton.setText(FontUtil.getTypefaceName(FontUtil.getSystemPath()));
        editorTypefaceButton.setText(FontUtil.getTypefaceName(FontUtil.getEditorPath()));

        FontUtil.applyFont(FontUtil.getSystemTypeface(), container, editorTypefaceButton, localTypefaceButton);
        editorTypefaceButton.setTypeface(FontUtil.getEditorTypeface());

        typefaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TypefacePicker dialog = TypefacePicker.newInstance(tempSettings.typefacePath, TypefacePicker.TYPE_SYSTEM);
                dialog.show(ctx.getSupportFragmentManager(), "TypefacePicker");
            }
        });

        editorTypefaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TypefacePicker dialog = TypefacePicker.newInstance(tempSettings.editorTypefacePath, TypefacePicker.TYPE_EDITOR);
                dialog.show(ctx.getSupportFragmentManager(), "TypefacePicker");
            }
        });

        localTypefaceButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TypefacePicker dialog = TypefacePicker.newInstance(localTempSettings.editorTypefacePath, TypefacePicker.TYPE_LOCAL);
                dialog.show(ctx.getSupportFragmentManager(), "TypefacePicker");
            }
        });

        Spinner editorFontSize = container.findViewById(R.id.editorFontSize);
        Spinner localFontSize = container.findViewById(R.id.localFontSize);

        editorFontSize.setAdapter(new ArrayAdapter<String>(ctx, R.layout.spinner_item, FontUtil.getEditorPointSizes()) {
            @Override
            public int getCount() { return super.getCount(); }

            @Override
            public View getView(int position, View view, ViewGroup parent) {
                TextView tv;
                if (view == null) {
                    tv = (TextView)((Activity) getContext()).getLayoutInflater().inflate(R.layout.spinner_item, parent, false);
                    tv.setTypeface(FontUtil.getSystemTypeface());
                    tv.setTextColor(colorCream);
                } else {
                    tv = (TextView) view;
                }
                tv.setText(getItem(position));

                return tv;
            }
        });
        ((ArrayAdapter)editorFontSize.getAdapter()).setDropDownViewResource(R.layout.spinner_item);

        localFontSize.setAdapter(new ArrayAdapter<String>(ctx, R.layout.spinner_item, FontUtil.getLocalEditorPointSizes()) {
            @Override
            public int getCount() { return super.getCount(); }

            @Override
            public View getView(int position, View view, ViewGroup parent) {
                TextView tv;
                if (view == null) {
                    tv = (TextView)((Activity) getContext()).getLayoutInflater().inflate(R.layout.spinner_item, parent, false);
                    tv.setTypeface(FontUtil.getSystemTypeface());
                    tv.setTextColor(colorCream);
                } else {
                    tv = (TextView) view;
                }
                tv.setText(getItem(position));

                return tv;
            }
        });
        ((ArrayAdapter)editorFontSize.getAdapter()).setDropDownViewResource(R.layout.spinner_item);

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
            container.findViewById(R.id.textDirLabel).setVisibility(View.GONE);
            container.findViewById(R.id.textDirGroup).setVisibility(View.GONE);
            container.findViewById(R.id.editorTextDirLabel).setVisibility(View.GONE);
            container.findViewById(R.id.editorTextDirGroup).setVisibility(View.GONE);
            container.findViewById(R.id.localTextDirLabel).setVisibility(View.GONE);
            container.findViewById(R.id.localTextDirGroup).setVisibility(View.GONE);
        }

        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P){
            container.findViewById(R.id.enableRoot).setVisibility(View.GONE);

            ((CheckBox) container.findViewById(R.id.enableHistory)).setTextColor(colorCream);
            ((CheckBox) container.findViewById(R.id.wordWrap)).setTextColor(colorCream);
            ((CheckBox) container.findViewById(R.id.lineNumbers)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.textDirLTR)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.textDirRTL)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorTextDirLTR)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorTextDirRTL)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorThemeLight)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorThemeDark)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorThemeBlack)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.aobClose)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.aobParent)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorAOSAsk)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorAOSFile)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.editorAOSContent)).setTextColor(colorCream);
            ((CheckBox) container.findViewById(R.id.enableRoot)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localWordWrapGlobal)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localWordWrapOn)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localWordWrapOff)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localLineNumberGlobal)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localLineNumberOn)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localLineNumberOff)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localTextDirGlobal)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localTextDirLTR)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localTextDirRTL)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localThemeGlobal)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localThemeLight)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localThemeDark)).setTextColor(colorCream);
            ((RadioButton) container.findViewById(R.id.localThemeBlack)).setTextColor(colorCream);
        }

        resetGlobalSettings();
    }

    public void open(boolean animate) {
        tempSettings = new TempSettings();
        resetGlobalSettings();

        if (ctx.getFrag() instanceof Editor) {
            container.findViewById(R.id.localButton).setVisibility(View.VISIBLE);
            Editor editor = (Editor)ctx.getFrag();
            localTempSettings = new TempSettings(editor.getSettings());
            resetLocalSettings(editor.getSettings());

            if (settingsAnimator.getDisplayedChild() == 0) {
                settingsAnimator.getInAnimation().setDuration(0);
                settingsAnimator.getOutAnimation().setDuration(0);
                settingsAnimator.setDisplayedChild(1);
            }
        } else {
            container.findViewById(R.id.localButton).setVisibility(View.INVISIBLE);
            if (settingsAnimator.getDisplayedChild() == 1) {
                settingsAnimator.getInAnimation().setDuration(0);
                settingsAnimator.getOutAnimation().setDuration(0);
                settingsAnimator.setDisplayedChild(0);
            }
        }

        super.open(animate);
    }

    public void close(boolean animate) {
        super.close(animate);

        handler.postDelayed(new Runnable() {
            public void run() {
                tempSettings = null;
                localTempSettings = null;
            }
        }, ANIMLENGTH);
    }

    private void resetGlobalSettings() {
        settingsAnimator.findViewById(R.id.settingsScroll).scrollTo(0, 0);
        settingsAnimator.findViewById(R.id.localSettingsScroll).scrollTo(0, 0);

        final TextView pathView = container.findViewById(R.id.startupDir);
        pathView.setText(Settings.getStartupPath() == null ? ctx.getText(R.string.permittedDirs) : Settings.getStartupPath().getPath());

        pathView.post(new Runnable() {
            public void run() {
                if (Settings.getSystemTextDirection() == Settings.TEXTDIR_RTL) {
                    ((HorizontalScrollView) pathView.getParent()).fullScroll(View.FOCUS_LEFT);
                } else
                    ((HorizontalScrollView) pathView.getParent()).fullScroll(View.FOCUS_RIGHT);
            }
        });

        ((CheckBox)container.findViewById(R.id.enableHistory)).setChecked(Settings.isSaveHistory());

        Button fontBrowse = container.findViewById(R.id.fontBrowse);
        fontBrowse.setTypeface(FontUtil.getSystemTypeface());
        fontBrowse.setText(FontUtil.getTypefaceName(FontUtil.getSystemPath()));

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (Settings.getSystemTextDirection() == Settings.TEXTDIR_LTR) {
                ((RadioGroup) container.findViewById(R.id.textDirGroup)).check(R.id.textDirLTR);
            } else
                ((RadioGroup) container.findViewById(R.id.textDirGroup)).check(R.id.textDirRTL);
        }

        Button editorFontBrowse = container.findViewById(R.id.editorFontBrowse);
        editorFontBrowse.setTypeface(FontUtil.getEditorTypeface());
        editorFontBrowse.setText(FontUtil.getTypefaceName(FontUtil.getEditorPath()));
        ((CheckBox)container.findViewById(R.id.wordWrap)).setChecked(Settings.isWordWrap());
        ((CheckBox)container.findViewById(R.id.lineNumbers)).setChecked(Settings.isShowLineNumbers());

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (Settings.getEditorTextDirection() == Settings.TEXTDIR_LTR) {
                ((RadioGroup) container.findViewById(R.id.editorTextDirGroup)).check(R.id.editorTextDirLTR);
            } else
                ((RadioGroup) container.findViewById(R.id.editorTextDirGroup)).check(R.id.editorTextDirRTL);
        }

        switch(Settings.getTheme()) {
            case Settings.THEME_DARK:
                ((RadioGroup) container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeDark);
                break;
            case Settings.THEME_BLACK:
                ((RadioGroup) container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeBlack);
                break;
            default:
                ((RadioGroup) container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeLight);
        }

        if (Settings.getActionOnBack() == Settings.AOB_PARENT) {
            ((RadioGroup) container.findViewById(R.id.aobGroup)).check(R.id.aobParent);
        } else
            ((RadioGroup) container.findViewById(R.id.aobGroup)).check(R.id.aobClose);

        switch(Settings.getActionOnShare()) {
            case Settings.AOS_FILE:
                ((RadioGroup) container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSFile);
                break;
            case Settings.AOS_CONTENT:
                ((RadioGroup) container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSContent);
                break;
            default:
                ((RadioGroup) container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSAsk);
        }

        ((CheckBox) container.findViewById(R.id.enableRoot)).setChecked(Settings.isEnableRoot());

        Spinner editorFontSize = container.findViewById(R.id.editorFontSize);
        editorFontSize.setSelection(FontUtil.getEditorSize() - 8);
    }

    private void resetLocalSettings(TxtSettings txtSettings) {
        Button fontBrowse = container.findViewById(R.id.localFontBrowse);
        fontBrowse.setText(txtSettings.typeface.isEmpty() ? ctx.getText(R.string.useglobal)
                    : FontUtil.getTypefaceName(txtSettings.typeface));
        fontBrowse.setTypeface(FontUtil.getTypefaceFromPath(txtSettings.typeface, FontUtil.getEditorTypeface()));

        switch(txtSettings.wordWrap) {
            case 0:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapOff);
                break;
            case 1:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapOn);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapGlobal);
        }

        switch(txtSettings.lineNumbers) {
            case 0:
                ((RadioGroup)container.findViewById(R.id.localLineNumberGroup)).check(R.id.localLineNumberOff);
                break;
            case 1:
                ((RadioGroup)container.findViewById(R.id.localLineNumberGroup)).check(R.id.localLineNumberOn);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.localLineNumberGroup)).check(R.id.localLineNumberGlobal);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            switch (txtSettings.textDirection) {
                case Settings.TEXTDIR_LTR:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirLTR);
                    break;
                case Settings.TEXTDIR_RTL:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirRTL);
                    break;
                default:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirGlobal);
            }
        }

        switch(txtSettings.theme) {
            case Settings.THEME_LIGHT:
                ((RadioGroup) container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeLight);
                break;
            case Settings.THEME_DARK:
                ((RadioGroup) container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeDark);
                break;
            case Settings.THEME_BLACK:
                ((RadioGroup) container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeBlack);
                break;
            default:
                ((RadioGroup) container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeGlobal);
        }

        Spinner localFontSize = container.findViewById(R.id.localFontSize);
        localFontSize.setSelection((txtSettings.pointSize < 0) ? 0 : txtSettings.pointSize - 7);
    }

    public void setStartupDirectory(AndPath newDirectory) {
        if ((Settings.getStartupPath() == null && newDirectory == null) || (Settings.getStartupPath() != null && Settings.getStartupPath().equals(newDirectory)))
            return;

        tempSettings.startupDir = newDirectory;
        final TextView pathView = container.findViewById(R.id.startupDir);
        pathView.setText(newDirectory == null ? ctx.getText(R.string.permittedDirs) : newDirectory.getPath());

        pathView.post(new Runnable() {
            public void run() {
                if (Settings.getSystemTextDirection() == Settings.TEXTDIR_RTL) {
                    ((HorizontalScrollView)pathView.getParent()).fullScroll(View.FOCUS_LEFT);
                } else
                    ((HorizontalScrollView)pathView.getParent()).fullScroll(View.FOCUS_RIGHT);
            }
        });
    }

    public void setSystemTypeface(String typefacePath) {
        Typeface typeface = FontUtil.getTypefaceFromPath(typefacePath, FontUtil.getDefault());
        tempSettings.typefacePath = typefacePath;
        Button fontButton = container.findViewById(R.id.fontBrowse);
        fontButton.setText(FontUtil.getTypefaceName(typefacePath));
        fontButton.setTypeface(typeface);
    }

    public void setEditorTypeface(String typefacePath) {
        Typeface typeface = FontUtil.getTypefaceFromPath(typefacePath, FontUtil.getEditorTypeface());
        tempSettings.editorTypefacePath = typefacePath;
        Button fontButton = container.findViewById(R.id.editorFontBrowse);
        fontButton.setText(FontUtil.getTypefaceName(typefacePath));
        fontButton.setTypeface(typeface);
    }

    public void setLocalTypeface(String typefacePath) {
        Typeface typeface = FontUtil.getTypefaceFromPath(typefacePath, FontUtil.getEditorTypeface());
        localTempSettings.typefacePath = typefacePath;
        localTempSettings.editorTypefacePath = typefacePath;
        Button fontButton = container.findViewById(R.id.localFontBrowse);
        fontButton.setText(typefacePath.isEmpty() ? ctx.getText(R.string.useglobal)
                : FontUtil.getTypefaceName(typefacePath));
        fontButton.setTypeface(typeface);
    }

    private void applySettings() {
        int textDirection;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            textDirection = ((RadioGroup) container.findViewById(R.id.textDirGroup))
                    .getCheckedRadioButtonId() == R.id.textDirRTL ? Settings.TEXTDIR_RTL : Settings.TEXTDIR_LTR;
            if (Settings.getSystemTextDirection() != textDirection) {
                Settings.setSystemTextDirection(textDirection);
                TextView pathView = container.findViewById(R.id.startupDir);
                pathView.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
                HorizontalScrollView.LayoutParams lp = (HorizontalScrollView.LayoutParams) pathView.getLayoutParams();
                if (Settings.getSystemTextDirection() == Settings.TEXTDIR_LTR) {
                    pathView.setTextDirection(View.TEXT_DIRECTION_LTR);
                    lp.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
                } else {
                    pathView.setTextDirection(View.TEXT_DIRECTION_RTL);
                    lp.gravity = Gravity.CENTER_VERTICAL | Gravity.RIGHT;
                }
                pathView.setLayoutParams(lp);
            }
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            textDirection = ((RadioGroup) container.findViewById(R.id.editorTextDirGroup))
                    .getCheckedRadioButtonId() == R.id.editorTextDirRTL ? Settings.TEXTDIR_RTL : Settings.TEXTDIR_LTR;
            if (Settings.getEditorTextDirection() != textDirection)
                Settings.setEditorTextDirection(textDirection);
        }

        int checkedRadioButtonId = ((RadioGroup) container.findViewById(R.id.editorThemeGroup)).getCheckedRadioButtonId();
        if (checkedRadioButtonId == R.id.editorThemeDark) {
            Settings.setTheme(Settings.THEME_DARK);
        } else if (checkedRadioButtonId == R.id.editorThemeBlack) {
            Settings.setTheme(Settings.THEME_BLACK);
        } else {
            Settings.setTheme(Settings.THEME_LIGHT);
        }

        int radioButtonId = ((RadioGroup) container.findViewById(R.id.editorAOSGroup)).getCheckedRadioButtonId();
        if (radioButtonId == R.id.editorAOSFile) {
            Settings.setActionOnShare(Settings.AOS_FILE);
        } else if (radioButtonId == R.id.editorAOSContent) {
            Settings.setActionOnShare(Settings.AOS_CONTENT);
        } else {
            Settings.setActionOnShare(Settings.AOS_ASK);
        }

        Settings.setActionOnBack(((RadioGroup) container.findViewById(R.id.aobGroup))
                .getCheckedRadioButtonId() == R.id.aobParent ? Settings.AOB_PARENT : Settings.AOB_CLOSE);

        Settings.setEnableRoot(((CheckBox) container.findViewById(R.id.enableRoot)).isChecked());

        Typeface tf = FontUtil.getTypefaceFromPath(tempSettings.typefacePath, FontUtil.getSystemTypeface());
        if (!FontUtil.getSystemTypeface().equals(tf)) {
            FontUtil.setSystemTypeface(tempSettings.typefacePath);
            FontUtil.applyFont(FontUtil.getSystemTypeface(), container,
                    container.findViewById(R.id.editorFontBrowse), container.findViewById(R.id.fontBrowse));
        }

        tf = FontUtil.getTypefaceFromPath(tempSettings.editorTypefacePath, FontUtil.getEditorTypeface());
        if (!FontUtil.getEditorTypeface().equals(tf))
            FontUtil.setEditorTypeface(tempSettings.editorTypefacePath);

        FontUtil.setEditorSize(((Spinner)container.findViewById(R.id.editorFontSize)).getSelectedItemPosition() + 8);

        if (tempSettings.startupDir == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
                Settings.setStartupPath(null);
        } else {
            Settings.setStartupPath(tempSettings.startupDir.getCurrent().exists()
                    ? tempSettings.startupDir : Settings.getStartupPath());
        }

        boolean saveHistory = ((CheckBox)container.findViewById(R.id.enableHistory)).isChecked();
        if (!saveHistory && Settings.isSaveHistory()) {
            Settings.clearHistory(ctx);
            Toast.makeText(ctx, ctx.getString(R.string.alert_historyCleared), Toast.LENGTH_SHORT).show();
        }
        Settings.setSaveHistory(saveHistory);

        Settings.setWordWrap(((CheckBox)container.findViewById(R.id.wordWrap)).isChecked());
        Settings.setShowLineNumbers(((CheckBox)container.findViewById(R.id.lineNumbers)).isChecked());

        Settings.saveSettings(ctx);

        ctx.getTabsWindow().applySettings();

        if (localTempSettings != null) {
            TxtSettings txtSettings = ((Editor)ctx.getFrag()).getSettings();
            txtSettings.typeface = localTempSettings.editorTypefacePath;

            int pointSize = ((Spinner)container.findViewById(R.id.localFontSize)).getSelectedItemPosition();
            txtSettings.pointSize = (pointSize == 0) ? -1 : pointSize + 7;

            int buttonId = ((RadioGroup) container.findViewById(R.id.localWordWrapGroup)).getCheckedRadioButtonId();
            if (buttonId == R.id.localWordWrapOn) {
                txtSettings.wordWrap = 1;
            } else if (buttonId == R.id.localWordWrapOff) {
                txtSettings.wordWrap = 0;
            } else {
                txtSettings.wordWrap = -1;
            }

            int id = ((RadioGroup) container.findViewById(R.id.localLineNumberGroup)).getCheckedRadioButtonId();
            if (id == R.id.localLineNumberOn) {
                txtSettings.lineNumbers = 1;
            } else if (id == R.id.localLineNumberOff) {
                txtSettings.lineNumbers = 0;
            } else {
                txtSettings.lineNumbers = -1;
            }

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
                int i = ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).getCheckedRadioButtonId();
                if (i == R.id.localTextDirLTR) {
                    txtSettings.textDirection = Settings.TEXTDIR_LTR;
                } else if (i == R.id.localTextDirRTL) {
                    txtSettings.textDirection = Settings.TEXTDIR_RTL;
                } else {
                    txtSettings.textDirection = -1;
                }
            } else
                txtSettings.textDirection = Settings.TEXTDIR_LTR;

            int i = ((RadioGroup) container.findViewById(R.id.localThemeGroup)).getCheckedRadioButtonId();
            if (i == R.id.localThemeLight) {
                txtSettings.theme = Settings.THEME_LIGHT;
            } else if (i == R.id.localThemeDark) {
                txtSettings.theme = Settings.THEME_DARK;
            } else if (i == R.id.localThemeBlack) {
                txtSettings.theme = Settings.THEME_BLACK;
            } else {
                txtSettings.theme = -1;
            }
        }

        ((SettingsApplicable)ctx.getFrag()).applySettings();
    }

    @Override
    public void setState(Bundle savedInstanceState) {
        super.setState(savedInstanceState);

        tempSettings = new TempSettings();
        if (ctx.getState() == TEditActivity.STATE_TEXT)
            localTempSettings = new TempSettings();

        int panel = savedInstanceState.getInt("TEdit.settingsWindow.panel", 0);
        panel = (panel > 1) ? 1 : (panel < 0) ? 0 : panel;
        if (ctx.getState() == TEditActivity.STATE_TEXT) {
            container.findViewById(R.id.localButton).setVisibility(View.VISIBLE);
        } else {
            if (panel == 1)
                panel = 0;
            container.findViewById(R.id.localButton).setVisibility(View.INVISIBLE);
        }
        settingsAnimator.getInAnimation().setDuration(0);
        settingsAnimator.getOutAnimation().setDuration(0);
        settingsAnimator.setDisplayedChild(panel);

        AndPath startupDir;
        try {
            startupDir = AndPath.fromJson(ctx,
                    savedInstanceState.getString("TEdit.settingsWindow.startupDir", ""));
        } catch (Exception e) {
            startupDir = null;
        }
        setStartupDirectory(startupDir);

        ((CheckBox)container.findViewById(R.id.enableHistory)).setChecked(savedInstanceState.getBoolean("TEdit.settingsWindow.saveHistory", false));

        setSystemTypeface(savedInstanceState.getString("TEdit.settingsWindow.typeface", FontUtil.DEFAULT_PATH));

        Spinner editorFontSize = container.findViewById(R.id.editorFontSize);
        editorFontSize.setSelection(savedInstanceState.getInt("TEdit.settingsWindow.editorFontSize", 15));

        int textDirection = savedInstanceState.getInt("TEdit.settingsWindow.textDirection", Settings.TEXTDIR_LTR);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (textDirection == Settings.TEXTDIR_LTR) {
                ((RadioGroup) container.findViewById(R.id.textDirGroup)).check(R.id.textDirLTR);
            } else
                ((RadioGroup) container.findViewById(R.id.textDirGroup)).check(R.id.textDirRTL);
        }
        setEditorTypeface(savedInstanceState.getString("TEdit.settingsWindow.editorTypeface", FontUtil.DEFAULT_PATH));
        ((CheckBox)container.findViewById(R.id.wordWrap))
                .setChecked(savedInstanceState.getBoolean("TEdit.settingsWindow.wordWrap", true));
        textDirection = savedInstanceState.getInt("TEdit.settingsWindow.editorTextDirection", Settings.TEXTDIR_LTR);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (textDirection == Settings.TEXTDIR_LTR) {
                ((RadioGroup) container.findViewById(R.id.editorTextDirGroup)).check(R.id.editorTextDirLTR);
            } else
                ((RadioGroup) container.findViewById(R.id.editorTextDirGroup)).check(R.id.editorTextDirRTL);
        }
        switch(savedInstanceState.getInt("TEdit.settingsWindow.editorTheme", Settings.THEME_LIGHT)) {
            case Settings.THEME_DARK:
                ((RadioGroup)container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeDark);
                break;
            case Settings.THEME_BLACK:
                ((RadioGroup)container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeBlack);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.editorThemeGroup)).check(R.id.editorThemeLight);
        }
        switch(savedInstanceState.getInt("TEdit.settingsWindow.editorAOS", Settings.AOS_ASK)) {
            case Settings.AOS_FILE:
                ((RadioGroup)container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSFile);
                break;
            case Settings.AOS_CONTENT:
                ((RadioGroup)container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSContent);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.editorAOSGroup)).check(R.id.editorAOSAsk);
        }

        if (localTempSettings == null)
            return;

        setLocalTypeface(savedInstanceState.getString("TEdit.settingsWindow.local.typeface", ""));

        Spinner localFontSize = container.findViewById(R.id.localFontSize);
        localFontSize.setSelection(savedInstanceState.getInt("TEdit.settingsWindow.localFontSize", 15));

        switch(savedInstanceState.getInt("TEdit.settingsWindow.local.wordWrap", -1)) {
            case 0:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapOff);
                break;
            case 1:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapOn);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.localWordWrapGroup)).check(R.id.localWordWrapGlobal);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            switch (savedInstanceState.getInt("TEdit.settingsWindow.local.textDirection", -1)) {
                case Settings.TEXTDIR_LTR:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirLTR);
                    break;
                case Settings.TEXTDIR_RTL:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirRTL);
                    break;
                default:
                    ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).check(R.id.localTextDirGlobal);
            }
        }
        switch(savedInstanceState.getInt("TEdit.settingsWindow.local.theme", -1)) {
            case Settings.THEME_LIGHT:
                ((RadioGroup)container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeLight);
                break;
            case Settings.THEME_DARK:
                ((RadioGroup)container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeDark);
                break;
            case Settings.THEME_BLACK:
                ((RadioGroup)container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeBlack);
                break;
            default:
                ((RadioGroup)container.findViewById(R.id.localThemeGroup)).check(R.id.localThemeGlobal);
        }
    }

    @Override
    public void saveState(Bundle outState) {
        if (!isOpen())
            return;

        outState.putInt("TEdit.settingsWindow.panel", settingsAnimator.getDisplayedChild());

        if (tempSettings.startupDir != null)
            outState.putString("TEdit.settingsWindow.startupDir", tempSettings.startupDir.toJson());
        outState.putBoolean("TEdit.settingsWindow.saveHistory", ((CheckBox)container.findViewById(R.id.enableHistory)).isChecked());
        outState.putString("TEdit.settingsWindow.typeface", tempSettings.typefacePath);
        int textDirection = ((RadioGroup)container.findViewById(R.id.textDirGroup))
                .getCheckedRadioButtonId() == R.id.textDirRTL ? Settings.TEXTDIR_RTL : Settings.TEXTDIR_LTR;
        outState.putInt("TEdit.settingsWindow.textDirection", textDirection);
        outState.putString("TEdit.settingsWindow.editorTypeface", tempSettings.editorTypefacePath);
        outState.putInt("TEdit.settingsWindow.editorFontSize", ((Spinner)container.findViewById(R.id.editorFontSize)).getSelectedItemPosition() + 8);
        outState.putBoolean("TEdit.settingsWindow.wordWrap", ((CheckBox)container.findViewById(R.id.wordWrap))
                .isChecked());
        textDirection = ((RadioGroup)container.findViewById(R.id.editorTextDirGroup))
                .getCheckedRadioButtonId() == R.id.editorTextDirRTL ? Settings.TEXTDIR_RTL : Settings.TEXTDIR_LTR;
        outState.putInt("TEdit.settingsWindow.editorTextDirection", textDirection);
        int checkedRadioButtonId = ((RadioGroup) container.findViewById(R.id.editorThemeGroup)).getCheckedRadioButtonId();
        if (checkedRadioButtonId == R.id.editorThemeDark) {
            outState.putInt("TEdit.settingsWindow.editorTheme", Settings.THEME_DARK);
        } else if (checkedRadioButtonId == R.id.editorThemeBlack) {
            outState.putInt("TEdit.settingsWindow.editorTheme", Settings.THEME_BLACK);
        } else {
            outState.putInt("TEdit.settingsWindow.editorTheme", Settings.THEME_LIGHT);
        }

        int radioButtonId = ((RadioGroup) container.findViewById(R.id.editorAOSGroup)).getCheckedRadioButtonId();
        if (radioButtonId == R.id.editorAOSFile) {
            outState.putInt("TEdit.settingsWindow.editorAOS", Settings.AOS_FILE);
        } else if (radioButtonId == R.id.editorAOSContent) {
            outState.putInt("TEdit.settingsWindow.editorAOS", Settings.AOS_CONTENT);
        } else {
            outState.putInt("TEdit.settingsWindow.editorAOS", Settings.AOS_ASK);
        }

        if (localTempSettings == null)
            return;

        outState.putString("TEdit.settingsWindow.local.typeface", localTempSettings.editorTypefacePath);
        outState.putInt("TEdit.settingsWindow.localFontSize", ((Spinner)container.findViewById(R.id.localFontSize)).getSelectedItemPosition() + 8);
        int buttonId = ((RadioGroup) container.findViewById(R.id.localWordWrapGroup)).getCheckedRadioButtonId();
        if (buttonId == R.id.localWordWrapOn) {
            outState.putInt("TEdit.settingsWindow.local.wordWrap", 1);
        } else if (buttonId == R.id.localWordWrapOff) {
            outState.putInt("TEdit.settingsWindow.local.wordWrap", 0);
        } else {
            outState.putInt("TEdit.settingsWindow.local.wordWrap", -1);
        }
        int id = ((RadioGroup) container.findViewById(R.id.localTextDirGroup)).getCheckedRadioButtonId();
        if (id == R.id.localTextDirLTR) {
            outState.putInt("TEdit.settingsWindow.local.textDirection", Settings.TEXTDIR_LTR);
        } else if (id == R.id.localTextDirRTL) {
            outState.putInt("TEdit.settingsWindow.local.textDirection", Settings.TEXTDIR_RTL);
        } else {
            outState.putInt("TEdit.settingsWindow.local.textDirection", -1);
        }
        int i = ((RadioGroup) container.findViewById(R.id.localThemeGroup)).getCheckedRadioButtonId();
        if (i == R.id.localThemeLight) {
            outState.putInt("TEdit.settingsWindow.local.theme", Settings.THEME_LIGHT);
        } else if (i == R.id.localThemeDark) {
            outState.putInt("TEdit.settingsWindow.local.theme", Settings.THEME_DARK);
        } else if (i == R.id.localThemeBlack) {
            outState.putInt("TEdit.settingsWindow.local.theme", Settings.THEME_BLACK);
        } else {
            outState.putInt("TEdit.settingsWindow.local.theme", -1);
        }
    }

    private class TempSettings {
        public AndPath startupDir = Settings.getStartupPath();
        public String typefacePath = FontUtil.getSystemPath();

        public String editorTypefacePath = FontUtil.getEditorPath();

        private TempSettings() {
        }

        private TempSettings(TxtSettings txtSettings) {
            if (txtSettings == null)
                return;

            typefacePath = txtSettings.typeface;
            editorTypefacePath = txtSettings.typeface;
        }
    }
}
