package cc.winboll.studio.regexputils;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.icu.text.SimpleDateFormat;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListPopupWindow;
import android.widget.TextView;
import android.widget.Toast;
import cc.winboll.studio.regexputils.develop.LogUtils;
import cc.winboll.studio.regexputils.develop.LogView;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends Activity {

    public static final String TAG = MainActivity.class.getSimpleName();

    TextView mtvPattern;
    EditText metPattern;
    TextView mtvRewrite;
    EditText metRewrite;
    TextView mtvMatchText;
    EditText metMatchText;
    TextView mtvResult;
    TextView mtvOnlineHelp;
    Button mbtnFavorite;
    WebView mWebView;
    URLEditText mURLEditText;
    SharedPreferences mSharedPreferences;
    Set<String> mSetStringFavorite;
    String mszDefaultOnlineHelp;
    LogView mLogView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mLogView = new LogView(this);
        LinearLayout mllLog = findViewById(R.id.activitymainLinearLayout1);
        mllLog.addView(mLogView);
        mLogView.startWatching();

        initView();

        LogUtils.d(TAG, "Created");

    }

    void initView() {
        //Toolbar toolbar= findViewById(R.id.toolbar);
        //setSupportActionBar(toolbar);

        mSharedPreferences = getSharedPreferences("SP", Context.MODE_PRIVATE);

        mtvPattern = findViewById(R.id.activitymainTextView2);
        metPattern = findViewById(R.id.activitymainEditText1);
        mtvRewrite = findViewById(R.id.activitymainTextView3);
        metRewrite = findViewById(R.id.activitymainEditText3);
        mtvMatchText = findViewById(R.id.activitymainTextView5);
        metMatchText = findViewById(R.id.activitymainEditText2);
        mtvResult = findViewById(R.id.activitymainTextView1);
        mWebView = findViewById(R.id.activitymainWebView1);
        mtvOnlineHelp = findViewById(R.id.activitymainTextView4);
        mURLEditText = findViewById(R.id.activitymainURLEditText1);
        mbtnFavorite = findViewById(R.id.activitymainButton1);

        mtvOnlineHelp.setText(getString(R.string.tv_onlinehelp));
        //系统默认会通过手机浏览器打开网页，为了能够直接通过WebView显示网页，则必须设置
        mWebView.setWebViewClient(new WebViewClient(){
                @Override
                public boolean shouldOverrideUrlLoading(WebView view, String url) {
                    //使用WebView加载显示url
                    view.loadUrl(url);
                    //返回true
                    return true;
                }
            });

        mSetStringFavorite = mSharedPreferences.getStringSet("mListFavorite", new HashSet<String>());
        String szURL = mSharedPreferences.getString("mWebView", getString(R.string.sz_defaultonlinehelp));
        addDefaultURLFavorite();
        mWebView.loadUrl(szURL);
        mWebView.setWebViewClient(new WebViewClient(){
                @Override
                public void onPageStarted(WebView view, String url, Bitmap favicon) {
                    //设定加载开始的操作
                    mURLEditText.setText(url);
                    for (String sz : mSetStringFavorite) {
                        if (sz.equals(url)) {
                            //mURLEditText.setFavoriteYes();
                            mbtnFavorite.setText("★");
                            return;
                        }
                    }
                    mbtnFavorite.setText("☆");
                    //mURLEditText.setFavoriteNo();
                }

            });
        mURLEditText.setText(szURL);
        mURLEditText.setOnEditorActionListener(
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        onGoto(null);
                    }
                    return false;
                }
            });
        /* mURLEditText.setOnTouchListener(new View.OnTouchListener() {
         @Override
         public boolean onTouch(View view, MotionEvent event) {
         final int DRAWABLE_LEFT = 0;
         //final int DRAWABLE_TOP = 1;
         final int DRAWABLE_RIGHT = 2;
         //final int DRAWABLE_BOTTOM = 3;
         if (event.getAction() == MotionEvent.ACTION_UP) {
         if (event.getX() >= (mURLEditText.getWidth() - mURLEditText
         .getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {

         return true;
         } else if (event.getX() <= (mURLEditText
         .getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) {

         return true;
         }
         }
         return false;
         }
         });*/
        mtvPattern.setText(getString(R.string.tv_pattern));
        metPattern.setText(mSharedPreferences.getString("metPattern", "[^n]"));
        metPattern.setOnEditorActionListener(
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        onRegExp(null);
                    }
                    return false;
                }
            });
        mtvRewrite.setText(getString(R.string.tv_rewrite));
        metRewrite.setText(mSharedPreferences.getString("metRewrite", ""));
        metRewrite.setOnEditorActionListener(
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        onRegExpRewrite(null);
                    }
                    return false;
                }
            });
        mtvMatchText.setText(getString(R.string.tv_matchtext));
        metMatchText.setText(mSharedPreferences.getString("metMatchText", "Test string 123."));
        metMatchText.setOnEditorActionListener(
            new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                    if (actionId == EditorInfo.IME_ACTION_DONE) {
                        onRegExp(null);
                    }
                    return false;
                }
            });

    }

    public void onEnableFavorite(View v) {
        changeURLFavorite();
    }

    public void onShowFavoriteList(View v) {
        showListPopulWindow();
    }

    void showListPopulWindow() {
        final String[] list = (String[])mSetStringFavorite.toArray(new String[0]);
        final ListPopupWindow listPopupWindow;
        listPopupWindow = new ListPopupWindow(this);
        listPopupWindow.setWidth(LayoutParams.WRAP_CONTENT);
        listPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
        listPopupWindow.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));//用android内置布局，或设计自己的样式
        //设置下拉列表基准控件
        listPopupWindow.setAnchorView(mURLEditText);
        listPopupWindow.setModal(true);
        // 透明度
        //listPopupWindow.setBackgroundDrawable(new ColorDrawable(0x00ffffff));
        listPopupWindow.setBackgroundDrawable(getDrawable(R.drawable.bg_shadow));

        listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置项点击监听
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mURLEditText.setText(list[i]);//展示选择的内容
                    setWebViewURL(list[i]);
                    listPopupWindow.dismiss();//如果已经选择了，隐藏起来
                }
            });
        listPopupWindow.show();//下拉列表展示出来
    }

    public void onRegExp(View v) {
        mtvResult.setText("");
        regExp();
        hideKeyboard(v);
    }

    public void onRegExpRewrite(View v) {
        mtvResult.setText("");
        regExpRewrite();
        hideKeyboard(v);
    }

    //隐藏虚拟键盘
    //
    public static void hideKeyboard(View v) {
        InputMethodManager imm = ( InputMethodManager ) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive()) {
            imm.hideSoftInputFromWindow(v.getApplicationWindowToken() , 0);

        }
    }

    // 获取当前时间格式化后的字符串
    //
    String getCurrentTimeString() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:SS");
        return sdf.format(System.currentTimeMillis());
    }

    ArrayList<String> regExp() {
        ArrayList<String> listResult = new ArrayList<String>();

        StringBuilder sbPrint = new StringBuilder();
        sbPrint.append(getString(R.string.sz_patternresult));
        sbPrint.append(" : ");
        sbPrint.append(getCurrentTimeString());

        // 输出当前累积的消息并清理 sbPrint
        mtvResult.append(sbPrint.toString());
        sbPrint = new StringBuilder("\n");

        try {
            String szMatchText = metMatchText.getText().toString();
            String szPattern = metPattern.getText().toString();
            mSharedPreferences = getSharedPreferences("SP", Context.MODE_PRIVATE);
            mSharedPreferences.edit().putString("metPattern", metPattern.getText().toString()).commit();
            mSharedPreferences.edit().putString("metMatchText", metMatchText.getText().toString()).commit();
            listResult = buildRegExpList(szMatchText, szPattern);
            if (listResult.size() > 0) {
                sbPrint.append("\nRegExp Result : ");
                sbPrint.append(listResult.size());
            } else {
                sbPrint.append("\nRegExp Result : 0");
            }
        } catch (Exception e) {
            LogUtils.d(TAG, "Exception : " + e.getMessage());
        }

        mtvResult.append(sbPrint.toString());

        LogUtils.d(TAG, "RegExp Done.");
        return listResult;
    }

    void regExpRewrite() {
        StringBuilder sbPrint = new StringBuilder("\n");
        try {
            String szMatchText = metMatchText.getText().toString();
            String szPattern = metPattern.getText().toString();
            String szRewrite = metRewrite.getText().toString();
            mSharedPreferences = getSharedPreferences("SP", Context.MODE_PRIVATE);
            mSharedPreferences.edit().putString("metPattern", metPattern.getText().toString()).commit();
            mSharedPreferences.edit().putString("metMatchText", metMatchText.getText().toString()).commit();
            mSharedPreferences.edit().putString("metRewrite", metRewrite.getText().toString()).commit();
            int nRewriteCount = regExpRewrite(szMatchText, szPattern, szRewrite);
            if (nRewriteCount > 0) {
                sbPrint.append("\nRewrite Result : ");
                sbPrint.append(nRewriteCount);
            } else {
                sbPrint.append("\nRewrite Result : 0");
            }
        } catch (Exception e) {
            LogUtils.d(TAG, "Exception : " + e.getMessage());
        }
        mtvResult.append(sbPrint);
        LogUtils.d(TAG, "RegExp Rewrite Done.");
    }

    // 
    // 生成语法模板匹配到的所有字符串数组
    //
    ArrayList<String> buildRegExpList(String szMatchText, String szPattern) {
        ArrayList<String> listResult = new ArrayList<String>();
        StringBuilder sbPrint = new StringBuilder("\n");

        Pattern pattern = Pattern.compile(szPattern, Pattern.MULTILINE);
        Matcher matcher = pattern.matcher(szMatchText);

        boolean isNull = true;
        int nStart = 0;
        while (matcher.find(nStart)) {
            isNull = false;
            int start = matcher.start();
            int end = matcher.end();
            String group = matcher.group();
            sbPrint.append("\n");
            sbPrint.append(getString(R.string.sz_start));
            sbPrint.append("(");
            sbPrint.append(Integer.toString(start));
            sbPrint.append(") ");
            sbPrint.append(getString(R.string.sz_end));
            sbPrint.append("(");
            sbPrint.append(Integer.toString(end));
            sbPrint.append(") >>> ");
            sbPrint.append(group);

            listResult.add(group);
            nStart = matcher.end();
        }

        mtvResult.append(sbPrint.toString());

        return listResult;
    }

    int regExpRewrite(String szMatchText, String szPattern, String szRewrite) {
        int nRewriteCount = 0;
        ArrayList<String> listResult = regExp();

        StringBuilder sbPrint = new StringBuilder("\n\n\n\n\n####################\n");
        sbPrint.append(getString(R.string.sz_rewriteresult));
        sbPrint.append(" : ");
        sbPrint.append(getCurrentTimeString());

        // 输出当前累积的消息并清理 sbPrint
        mtvResult.append(sbPrint.toString());
        sbPrint = new StringBuilder();

        for (int i = 0; i < listResult.size(); i++) {
            Pattern pattern = Pattern.compile(szPattern, Pattern.MULTILINE);
            Matcher matcher = pattern.matcher(listResult.get(i));
            if (matcher.find()) {
                nRewriteCount++;
                sbPrint.append("\n Rewrite ");
                sbPrint.append(nRewriteCount);
                sbPrint.append(" : \n");
                sbPrint.append(matcher.replaceAll(szRewrite));
                sbPrint.append(" \n");
            }
        }

        mtvResult.append(sbPrint.toString());
        return nRewriteCount;
    }

    @Override
    protected void onDestroy() {
        mLogView.stopWatching();

        mSharedPreferences.edit().putString("metPattern", metPattern.getText().toString()).commit();
        mSharedPreferences.edit().putString("metMatchText", metMatchText.getText().toString()).commit();
        mSharedPreferences.edit().putStringSet("mListFavorite", mSetStringFavorite).commit();

        super.onDestroy();
    }

    void changeURLFavorite() {
        //String szURL = getString(R.string.webview_helpurl);
        //setWebViewURL(szURL);
        String url = mURLEditText.getText().toString();

        // 转换收藏开关
        for (String sz : mSetStringFavorite) {
            if (sz.equals(url)) {
                // 保护默认URL
                if (!getString(R.string.sz_defaultonlinehelp).equals(url)) {
                    mSetStringFavorite.remove(sz);
                    //mURLEditText.setFavoriteNo();
                    mbtnFavorite.setText("☆");
                    mSharedPreferences.edit().putStringSet("mListFavorite", mSetStringFavorite).commit();
                    return;
                } else {
                    Toast.makeText(getApplication(), "!☆", Toast.LENGTH_SHORT).show();
                }
            }
        }
        mSetStringFavorite.add(url);
        mbtnFavorite.setText("★");
        //mURLEditText.setFavoriteYes();
        mSharedPreferences.edit().putStringSet("mListFavorite", mSetStringFavorite).commit();
    }

    void addDefaultURLFavorite() {
        //String szURL = getString(R.string.webview_helpurl);
        //setWebViewURL(szURL);
        String szDefault = getString(R.string.sz_defaultonlinehelp);

        // 转换收藏开关
        for (String sz : mSetStringFavorite) {
            if (sz.equals(szDefault)) {
                return;
            }
        }
        mSetStringFavorite.add(szDefault);
        //mURLEditText.setFavoriteYes();
        mbtnFavorite.setText("★");
        mSharedPreferences.edit().putStringSet("mListFavorite", mSetStringFavorite).commit();
    }

    public void onGoto(View v) {
        setWebViewURL(mURLEditText.getText().toString());
    }

    void setWebViewURL(String szURL) {
        mSharedPreferences.edit().putString("mWebView", szURL).commit();
        mWebView.loadUrl(szURL);
        mURLEditText.setText(szURL);
    }

    public void onCleanLog(View view) {
        LogUtils.cleanLog();
        LogUtils.d(TAG, "Log cleaned");
    }
}
