package tech.starwin.utils.format_utils;

import android.app.Activity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.TextView;

import java.util.Stack;

/**
 * Created by SiKang on 2019/5/23.
 */
public class StringDecrypt {
    public static final String FLAG = "#-#";

    public static String uncodeString(String text) {
        try {
            if (text.contains(FLAG)) {
                String key = text.split(FLAG)[0];
                String value = text.split(FLAG)[1];
                value = new String(Base64.decode(value.getBytes(), Base64.DEFAULT));
                if (value.startsWith(key)) {
                    value = value.replace(key + "#-#", "");
                }
                return value;
            }
        } catch (Exception e) {
            Log.d("StringDecrypt", text);
        }
        return text;
    }


    public static void encode(Activity activity) {
        View rootView = ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
        encode((ViewGroup) rootView);
    }

    public static void encode(ViewGroup viewGroup) {
        try {
            int count = viewGroup.getChildCount();
            for (int i = 0; i < count; i++) {
                View view = viewGroup.getChildAt(i);
                if (view instanceof ViewGroup) {
                    encode((ViewGroup) view);
                } else if (view instanceof TextView) {
                    TextView textView = (TextView) view;
                    String text = StringDecrypt.uncodeString(textView.getText().toString());
                    textView.setText(text);
                    if (textView.getHint() != null) {
                        String hint = StringDecrypt.uncodeString(textView.getHint().toString());
                        textView.setHint(hint);
                    }
                }
            }
        } catch (Exception e) {
            Log.e("StringDecrypt", "can not update View!");
        }
    }

    public static void uncode(TextView textView) {
        String text = uncodeString(textView.getText().toString());
        textView.setText(text);
    }

    public static void uncode(EditText editText) {
        String text = uncodeString(editText.getText().toString());
        editText.setText(text);
    }
}
