package cc.winboll.studio.webpagesources;

/**
 * @Author ZhanGSKen@QQ.COM
 * @Date 2023/07/02 17:10:46
 * @Describe 主要启动窗口类
 */
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.ValueCallback;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import cc.winboll.studio.libappbase.GlobalApplication;
import cc.winboll.studio.libappbase.LogUtils;
import cc.winboll.studio.libappbase.winboll.IWinBoLLActivity;
import cc.winboll.studio.webpagesources.R;
import cc.winboll.studio.webpagesources.activities.AboutActivity;
import cc.winboll.studio.webpagesources.fragment.SourcesFragment;
import cc.winboll.studio.webpagesources.fragment.WebFragment;
import cc.winboll.studio.webpagesources.view.StatusBarView;
import com.hjq.toast.ToastUtils;

public class MainActivity extends AppCompatActivity implements IWinBoLLActivity {

    public static final String TAG = "MainActivity";

    public static final int REQUEST_ABOUT_ACTIVITY = 0;
    public static final int REQUEST_FILE_CHOOSER = 1;

    public static final String MSG_UPDATE_URL = "MSG_UPDATE_URL";

    static MainActivity _MainActivity;
    StatusBarView mStatusBarView;
    WebFragment mWebFragment;
    SourcesFragment mSourcesFragment;
    static boolean _mIsLoadedHomePage;

    @Override
    public Activity getActivity() {
        return this;
    }

    @Override
    public String getTag() {
        return TAG;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FragmentTransaction ft = ((FragmentManager)getSupportFragmentManager()).beginTransaction();
        mSourcesFragment = new SourcesFragment();
        ft.add(R.id.activitymainFrameLayout1, mSourcesFragment, SourcesFragment.TAG);
        ft.hide(mSourcesFragment);
        mWebFragment = new WebFragment();
        //mWebFragment.setJSOnShowSourceListener(this);
        ft.add(R.id.activitymainFrameLayout1, mWebFragment, WebFragment.TAG);
        ft.show(mWebFragment);
        ft.commit();

        mStatusBarView = findViewById(R.id.activitymainStatusBarView1);
        _MainActivity = this;
        postStatusBarMessage("主窗口加载完成。");
        //ToastUtils.show("Start");
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        // 处理 onNewIntent 时的 Intent（Activity 已存在时调用）
//        handleIntent(intent);
//    }

    private String getIntentUrl(Intent intent) {
        if (Intent.ACTION_VIEW.equals(intent.getAction())) {
            //ToastUtils.show("ACTION_VIEW");
            Uri data = intent.getData();
            if (data != null) {
                String url = data.toString(); // 获取完整 URL
                String host = data.getHost(); // 获取主机名（如 "www.example.com"）
                String path = data.getPath(); // 获取路径（如 "/page"）

                // 在界面显示 URL
                //tvUrl.setText("接收到的 URL：\n" + url);
                //ToastUtils.show(String.format("url %s", url));
                return url;

                // 示例：打开系统浏览器访问该 URL
                // Intent browserIntent = new Intent(Intent.ACTION_VIEW, data);
                // startActivity(browserIntent);
            }
        }
        return null;
    }

    public static void postStatusBarMessage(String msg) {
        if (_MainActivity != null) {
            _MainActivity.mStatusBarView.postMessage(msg);
        }
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        String intentUrl = getIntentUrl(getIntent());
        if (intentUrl != null && !intentUrl.trim().equals("")) {
            mWebFragment.loadUrl(intentUrl);
        } else {
            if (_mIsLoadedHomePage) {
                //ToastUtils.show("重新加载当前页面");
                mWebFragment.reloadLastUrl();
            } else {
                //ToastUtils.show("加载默认主页");
                mWebFragment.loadUrl(getApplicationContext().getString(R.string.app_homepage));
                _mIsLoadedHomePage = true;
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        //return super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
            case R.id.item_sources : {
                    LogUtils.d(TAG, "item_web");
                    FragmentTransaction ft = ((FragmentManager)getSupportFragmentManager()).beginTransaction();
                    ft.hide(mWebFragment);
                    ft.show(mSourcesFragment);
                    ft.commit();
                    break;
                }
            case R.id.item_web : {
                    LogUtils.d(TAG, "item_sources");
                    FragmentTransaction ft = ((FragmentManager)getSupportFragmentManager()).beginTransaction();
                    ft.hide(mSourcesFragment);
                    ft.show(mWebFragment);
                    ft.commit();
                    break;
                }
            case R.id.item_editor : {
                    mSourcesFragment.shareHtml();
                    break;
                }
            case R.id.item_log : {
                    GlobalApplication.getWinBoLLActivityManager().startLogActivity(this);
                    break;
                }
            case R.id.item_about : {
                    GlobalApplication.getWinBoLLActivityManager().startWinBoLLActivity(this, AboutActivity.class);
                    break;
                }
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //ToastUtils.show("onActivityResult Main");
        switch (requestCode) {
            case REQUEST_ABOUT_ACTIVITY : {
                    LogUtils.d(TAG, "REQUEST_ABOUT_ACTIVITY");
                    break;
                }
            case REQUEST_FILE_CHOOSER : {
                    //ToastUtils.show("MainActivity.REQUEST_FILE_CHOOSER");
                    ValueCallback<Uri[]> filePathCallback = mWebFragment.getWebView().getFilePathCallback();

                    if (filePathCallback == null) {
                        return;
                    }

                    Uri[] results = null;
                    // 检查选择的文件是否为空
                    if (resultCode == Activity.RESULT_OK && data != null) {
                        String dataString = data.getDataString();
                        if (dataString != null) {
                            results = new Uri[]{Uri.parse(dataString)};
                        }
                    }

                    // 传递选择的文件给WebView
                    filePathCallback.onReceiveValue(results);
                    filePathCallback = null;

                    break;
                }
            default : {
                    super.onActivityResult(requestCode, resultCode, data);
                }
        }
    }
}
