package com.remax.visualnovel.app.widget.tips;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.remax.visualnovel.R;
import com.remax.visualnovel.extension.ViewExtKt;


public class TipsPopWindow {

    private PopupWindow popupWindow;

    public TipsPopWindow build(Context context, String content, int width) {
        View view = LayoutInflater.from(context).inflate(R.layout.popwindow_tips, null);
        popupWindow = new PopupWindow(context);
        popupWindow.setFocusable(true);
        popupWindow.setContentView(view);
        if (width != ViewGroup.LayoutParams.MATCH_PARENT) {
            ViewExtKt.setMargin(view, 0, 0, 0, 0);
            TextView tv = view.findViewById(R.id.tvContent);
            textWidth = tv.getPaint().measureText(content);
        }
        popupWindow.setWidth(width);
        popupWindow.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable());

        TextView tvContent = view.findViewById(R.id.tvContent);
        tvContent.setText(content);
        return this;
    }

    private float textWidth;

    public float getTextWidth() {
        return textWidth;
    }

    public TipsPopWindow build(Context context, String content) {
        return build(context, content, ViewGroup.LayoutParams.MATCH_PARENT);
    }

    public TipsPopWindow build(Context context, int resId) {
        return build(context, context.getString(resId));
    }

    public void showAsDropDown(View view) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(view);
        }
    }

    public void showAsDropDown(View view, int xoff, int yoff) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAsDropDown(view, xoff, yoff);
        }
    }

    public void showAtLocation(View parent, int gravity, int x, int y) {
        if (popupWindow.isShowing()) {
            popupWindow.dismiss();
        } else {
            popupWindow.showAtLocation(parent, gravity, x, y);
        }
    }
}
