package cc.winboll.studio.webpagesources.view;

/**
 * @Author ZhanGSKen@QQ.COM
 * @Date 2023/07/16 17:52:43
 * @Describe 网页地址栏
 */
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.JsonReader;
import android.util.JsonWriter;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import androidx.appcompat.widget.ListPopupWindow;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.webpagesources.R;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class URLAddressView extends LinearLayout {

    public static final String TAG = "URLEditText";

    Context mContext;
    EditText mURLAddressEditText;
    ImageView mRightImageView;
    ImageView mLeftImageView;
    ListPopupWindow mListPopupWindow;
    boolean mIsListPopupWindow_OnShow = false;
    long mnRightImageViewTouchCount = 0;
    String mszConfigPath;
    ArrayList<URLInfo> mlistURLInfo;
    //Drawable drawable_r;
    //Drawable drawable_l_no;
    //Drawable drawable_l_yes;
    LinearLayout mllAnchorView;

    /**
     * 在java代码里new的时候会用到
     * @param context
     */
    public URLAddressView(Context context) {
        super(context);
        init(context);
    }

    /**
     * 在xml布局文件中使用时自动调用
     * @param context
     */
    public URLAddressView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    /**
     * 不会自动调用，如果有默认style时，在第二个构造函数中调用
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public URLAddressView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    /**
     * 只有在API版本>21时才会用到
     * 不会自动调用，如果有默认style时，在第二个构造函数中调用
     * @param context
     * @param attrs
     * @param defStyleAttr
     * @param defStyleRes
     */
    //@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public URLAddressView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context);
    }

    public void initAnchorView(LinearLayout llAnchorView) {
        mllAnchorView = llAnchorView;
    }

    void init(Context context) {
        mContext = context;
        View viewMain = inflate(mContext, R.layout.view_urladdress, null);
        mURLAddressEditText = viewMain.findViewById(R.id.viewurladdressEditText1);
        mLeftImageView = viewMain.findViewById(R.id.viewurladdressImageView1);
        mRightImageView = viewMain.findViewById(R.id.viewurladdressImageView2);
        addView(viewMain);

        mszConfigPath = context.getExternalFilesDir(TAG) + File.separator + "_mszConfigPath.json";
        mlistURLInfo = new ArrayList<URLInfo>();
        mlistURLInfo = loadListURLInfo();

        mURLAddressEditText.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) {
                    // 当文本发生改变时，这个方法会被调用
                    //LogUtils.d(TAG, "Text changed to: " + s.toString());
                    for (int i = 0; i < 0; i++) {
                        if (mURLAddressEditText.equals(mlistURLInfo.get(i).getUrl())) {
                            updateFavoriteButtonStatus();
                            return;
                        }
                    }

                    updateFavoriteButtonStatus();
                    /*if (mIOnTextChanged != null) {
                     if (text != null) {
                     mIOnTextChanged.onTextChanged(text.toString());
                     }
                     }*/
                }

                @Override
                public void afterTextChanged(Editable s) {}
            });
            
        mURLAddressEditText.setOnTouchListener(new View.OnTouchListener(){

                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        //ToastUtils.show("mURLAddressEditText ACTION_DOWN");
                        if(!mIsListPopupWindow_OnShow) {
                            mnRightImageViewTouchCount = 0;
                        }
                    }
                    return false;
                }
            });

        mLeftImageView.setOnTouchListener(new View.OnTouchListener(){

                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        changeURLFavoriteStatus(mURLAddressEditText.getText().toString());
                    } else {
                        LogUtils.d(TAG, "MotionEvent : " + Integer.toString(motionEvent.getAction()));
                    }
                    return false;
                }
            });

        mRightImageView.setOnTouchListener(new View.OnTouchListener(){

                @Override
                public boolean onTouch(View view, MotionEvent motionEvent) {
                    if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                        if (mnRightImageViewTouchCount % 2 == 0) {
                            // 弹出网址列表
                            showListPopulWindow();
                        }
                        mnRightImageViewTouchCount++;
                    } else {
                        LogUtils.d(TAG, "MotionEvent : " + Integer.toString(motionEvent.getAction()));
                    }
                    return false;
                }
            });

        /*TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.test);
         String text = ta.getString(R.styleable.test_text);
         setText(text + " ZhanGSKen.CN");
         ta.recycle();*/
        //drawable_r = getResources().getDrawable(R.drawable.ic_form_dropdown);
        //drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(),drawable_n.getMinimumHeight());  //此为必须写的
        //drawable_r.setBounds(0, 0, 80, 80);  //此为必须写的

        //drawable_l_no = getResources().getDrawable(R.drawable.ic_favorite_outline);
        //drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(),drawable_n.getMinimumHeight());  //此为必须写的
        //drawable_l_no.setBounds(0, 0, 80, 80);  //此为必须写的

        //drawable_l_yes = getResources().getDrawable(R.drawable.ic_favorite);
        //drawable_n.setBounds(0, 0, drawable_n.getMinimumWidth(),drawable_n.getMinimumHeight());  //此为必须写的
        //drawable_l_yes.setBounds(0, 0, 80, 80);  //此为必须写的

        //setFavoriteNo();
        //setOnTouchListener(mOnTouchListener);
        //setMinWidth(100);
        //setPadding(10,0,10,0);
        //setPaddingRelative(0,0,0,0);
        
    }
    
    public String getURLAddressText() {
        return mURLAddressEditText.getText().toString();
    }

    public void setURLAddressText(String szUrl) {
        mURLAddressEditText.setText(szUrl);
    }

    //
    // 更新收藏按钮显示状态
    //
    void updateFavoriteButtonStatus() {
        if (isFavoritedURL(mURLAddressEditText.getText().toString())) {
            mLeftImageView.setBackgroundResource(R.drawable.ic_favorite);
            //setCompoundDrawables(drawable_l_yes, null, drawable_r, null);
        } else {
            mLeftImageView.setBackgroundResource(R.drawable.ic_favorite_outline);
            //setCompoundDrawables(drawable_l_no, null, drawable_r, null);
        }

    }

    /*@Override
     public void setOnTouchListener(View.OnTouchListener l) {
     super.setOnTouchListener(l);
     }*/

    /*View.OnTouchListener mOnTouchListener = 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() >= (getWidth() - getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width())) {
     // 弹出网址列表
     LogUtils.d(TAG, "mOnTouchListener 1");
     showListPopulWindow();
     return false;
     } else if (event.getX() <= (getCompoundDrawables()[DRAWABLE_LEFT].getBounds().width())) {
     // 修改输入框网址收藏状态
     LogUtils.d(TAG, "mOnTouchListener 2");
     changeURLFavoriteStatus(getText().toString());
     return false;
     }
     }
     return false;
     }
     };*/

    //
    // 改变网址的收藏状态：
    // @返回值：收藏状态
    //        如果没收藏就设置收藏，收藏状态返回true;
    //        如果收藏了就取消收藏，收藏状态返回false;
    //
    public boolean changeURLFavoriteStatus(String szUrl) {
        if (szUrl == null || szUrl.equals("")) {
            return false;
        }

        for (URLInfo item : mlistURLInfo) {
            if (item.getUrl().equals(szUrl)) {
                mlistURLInfo.remove(item);
                saveListURLInfo();
                updateFavoriteButtonStatus();
                return false;
            }
        }

        URLInfo newItem = new URLInfo(szUrl);
        mlistURLInfo.add(newItem);
        saveListURLInfo();
        updateFavoriteButtonStatus();
        return true;
    }

    //
    // 读取网址的收藏状态
    //
    public boolean isFavoritedURL(String szUrl) {
        if ((mlistURLInfo == null) || (szUrl == null) || szUrl.equals("")) {return false;}

        for (URLInfo item : mlistURLInfo) {
            if (item.getUrl().equals(szUrl)) {
                return true;
            }
        }
        return false;
    }

    //
    // 前置网址在收藏列表里的位置
    //
    public boolean postposesURL(String szUrl) {
        for (URLInfo item : mlistURLInfo) {
            if (item.getUrl().equals(szUrl)) {
                mlistURLInfo.add(0, new URLInfo(szUrl));
                mlistURLInfo.remove(item);
                saveListURLInfo();
                return true;
            }
        }
        return false;
    }

    //
    // 加载收藏的网址列表
    //
    public ArrayList<URLInfo> loadListURLInfo() {
        File fJson = new File(mszConfigPath);
        try {
            ArrayList<URLInfo> listTemp = readJsonStream(new FileInputStream(fJson));
            if (listTemp != null && listTemp.size() > 0) {
                mlistURLInfo.clear();
                mlistURLInfo.addAll(listTemp);
            } else {
                mlistURLInfo.clear();
                saveListURLInfo();
            }
        } catch (IOException e) {
            LogUtils.d(TAG, "IOException : " + e.getMessage());
            mlistURLInfo = new ArrayList<URLInfo>();
            saveListURLInfo();
        }
        return mlistURLInfo;
    }

    //
    // 读取 Json 文件
    //
    ArrayList<URLInfo> readJsonStream(InputStream in) throws IOException {
        JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8"));
        return readURLInfoArrayList(reader);
    }

    //
    // 读取 Json 文件的每一 Json 项
    //
    ArrayList<URLInfo> readURLInfoArrayList(JsonReader reader) throws IOException {
        ArrayList<URLInfo> list = new ArrayList<URLInfo>();
        reader.beginArray();
        while (reader.hasNext()) {
            list.add(readURLInfo(reader));
        }
        reader.endArray();
        return list;
    }

    //
    // 读取 Json 文件的某一 Json 项
    //
    URLInfo readURLInfo(JsonReader reader) throws IOException {
        URLInfo urlInfo = new URLInfo();
        reader.beginObject();
        while (reader.hasNext()) {
            String name = reader.nextName();
            if (name.equals("url")) {
                urlInfo.setUrl(reader.nextString());
            } else {
                reader.skipValue();
            }
        }
        reader.endObject();
        return urlInfo;
    }

    //
    // 写入 Json 文件的某一 Json 项
    //
    static void writeConfigs(JsonWriter writer, URLInfo urlInfo) throws IOException {
        writer.beginObject();
        writer.name("url").value(urlInfo.getUrl());
        writer.endObject();
    }

    //
    // 保存收藏的网址列表
    //
    void saveListURLInfo() {
        try {
            File fJson = new File(mszConfigPath);
            writeJsonStream(new FileOutputStream(fJson, false), mlistURLInfo);
        } catch (IOException e) {
            LogUtils.d(TAG, "IOException : " + e.getMessage());
        }
    }

    //
    // 写入 Json 文件
    //
    void writeJsonStream(OutputStream out, ArrayList<URLInfo> listURLInfo) throws IOException {
        JsonWriter writer = new JsonWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.setIndent("  ");
        writeConfigsArray(writer, listURLInfo);
        writer.close();
    }

    //
    // 记录 Json 文件的某一 Json 项
    //
    void writeConfigsArray(JsonWriter writer, ArrayList<URLInfo> listURLInfo) throws IOException {
        writer.beginArray();
        for (URLInfo urlInfo : listURLInfo) {
            writeConfigs(writer, urlInfo);
        }
        writer.endArray();
    }

    public class URLInfo {
        String url;

        public URLInfo() {}
        public URLInfo(String url) {
            this.url = url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getUrl() {
            return url;
        }
    }

    //
    // 弹出网址下拉框
    // @ llAnchorView : 设置下拉列表基准控件
    //
    void showListPopulWindow() {
        //final String[] list = {"asg","hshsh"};
        int nListSize = mlistURLInfo.size();
        final String[] list = new String[nListSize];
        for (int i = 0; i < nListSize; i++) {
            list[i] = mlistURLInfo.get(i).getUrl();
        }
        //final String[] list = (String[])mSetStringFavorite.toArray(new String[0]);


        mListPopupWindow = new ListPopupWindow(mContext);
        mListPopupWindow.setWidth(LayoutParams.WRAP_CONTENT);
        mListPopupWindow.setHeight(LayoutParams.WRAP_CONTENT);
        //listPopupWindow.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list));//用android内置布局，或设计自己的样式
        mListPopupWindow.setAdapter(new ArrayAdapter<String>(mContext, R.layout.view_popurllist, R.id.viewpopurllistTextView1, list));//用android内置布局，或设计自己的样式
        //设置下拉列表基准控件
        //LinearLayout llAnchorView = findViewById(R.id.activitytesturlLinearLayout2);
        mListPopupWindow.setAnchorView(mllAnchorView);
        mListPopupWindow.setModal(false);
        // 透明度
        //listPopupWindow.setBackgroundDrawable(new ColorDrawable(0xEEAAAAAA));
        mListPopupWindow.setBackgroundDrawable(mContext.getDrawable(R.drawable.bg_shadow));

        mListPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {//设置项点击监听
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    mURLAddressEditText.setText(list[i]);//展示选择的内容
                    postposesURL(list[i]);
                    updateFavoriteButtonStatus();
                    //setWebViewURL(list[i]);
                    mListPopupWindow.dismiss();//如果已经选择了，隐藏起来
                    mnRightImageViewTouchCount = 0;
                }
            });
        mListPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener(){
                @Override
                public void onDismiss() {
                    mIsListPopupWindow_OnShow = false;
                }
            });
        mIsListPopupWindow_OnShow = true;
        mListPopupWindow.show();//下拉列表展示出来
    }
}
