package com.beautypol.shell;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.view.View;
import android.view.Gravity;
import android.webkit.*;
import android.widget.*;
import org.json.*;
import java.nio.charset.StandardCharsets;
import java.util.HashSet;
import java.util.Set;

public class MainActivity extends Activity {
    private WebView web;
    private String website;
    private final Set<String> allowedHosts = new HashSet<>();
    private FrameLayout root;
    @Override public void onCreate(Bundle state) {
        super.onCreate(state);
        try {
            JSONObject brand = new JSONObject(readAsset("brand.json"));
            website = brand.getString("website_url");
            JSONArray hosts=brand.getJSONArray("allowed_hosts");
            for(int i=0;i<hosts.length();i++) allowedHosts.add(hosts.getString(i));
            root=new FrameLayout(this);root.setBackgroundColor(Color.parseColor(brand.getString("background_color")));setContentView(root);
            root.setOnApplyWindowInsetsListener((v,insets)->{v.setPadding(insets.getSystemWindowInsetLeft(),insets.getSystemWindowInsetTop(),insets.getSystemWindowInsetRight(),insets.getSystemWindowInsetBottom());return insets;});
            web=new WebView(this);root.addView(web,new FrameLayout.LayoutParams(-1,-1));
            WebView.setWebContentsDebuggingEnabled(false);
            WebSettings settings=web.getSettings();settings.setJavaScriptEnabled(true);settings.setDomStorageEnabled(true);settings.setAllowFileAccess(false);settings.setAllowContentAccess(false);settings.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);settings.setSafeBrowsingEnabled(true);settings.setSupportMultipleWindows(false);
            CookieManager.getInstance().setAcceptThirdPartyCookies(web,false);
            web.setWebViewClient(new WebViewClient(){
                @Override public boolean shouldOverrideUrlLoading(WebView view,WebResourceRequest req){Uri uri=req.getUrl();if("https".equals(uri.getScheme())&&allowedHosts.contains(uri.getHost()))return false;if(req.isForMainFrame()&&( "https".equals(uri.getScheme())||"http".equals(uri.getScheme())||"tel".equals(uri.getScheme()))){try{startActivity(new Intent(Intent.ACTION_VIEW,uri));}catch(Exception ignored){}}return true;}
                @Override public void onReceivedSslError(WebView view,SslErrorHandler handler,SslError error){handler.cancel();showOffline();}
                @Override public void onReceivedError(WebView view,WebResourceRequest req,WebResourceError error){if(req.isForMainFrame())showOffline();}
            });
            web.loadUrl(website);
            LinearLayout splash=new LinearLayout(this);splash.setOrientation(LinearLayout.VERTICAL);splash.setGravity(Gravity.CENTER);splash.setBackgroundColor(Color.parseColor(brand.getString("background_color")));
            ImageView picture=new ImageView(this);picture.setImageResource(R.drawable.splash_image);picture.setScaleType(ImageView.ScaleType.FIT_CENTER);splash.addView(picture,new LinearLayout.LayoutParams(-1,0,1));
            TextView label=new TextView(this);label.setText(brand.optString("splash_text",brand.getString("app_name")));label.setTextColor(Color.parseColor(brand.getString("primary_color")));label.setTextSize(24);label.setGravity(Gravity.CENTER);label.setPadding(20,20,20,40);splash.addView(label);root.addView(splash,new FrameLayout.LayoutParams(-1,-1));
            new Handler(Looper.getMainLooper()).postDelayed(()->root.removeView(splash),brand.optInt("splash_ms",1500));
        }catch(Exception ex){TextView error=new TextView(this);error.setText("تنظیمات برنامه معتبر نیست.");setContentView(error);}
    }
    private String readAsset(String name) throws java.io.IOException {try(java.io.InputStream input=getAssets().open(name);java.io.ByteArrayOutputStream output=new java.io.ByteArrayOutputStream()){byte[] buffer=new byte[4096];int length;while((length=input.read(buffer))!=-1)output.write(buffer,0,length);return new String(output.toByteArray(),StandardCharsets.UTF_8);}}
    private void showOffline(){runOnUiThread(()->{LinearLayout panel=new LinearLayout(this);panel.setOrientation(LinearLayout.VERTICAL);panel.setGravity(Gravity.CENTER);panel.setBackgroundColor(Color.WHITE);TextView message=new TextView(this);message.setText("اتصال امن برقرار نشد. اینترنت خود را بررسی کنید.");message.setPadding(24,24,24,24);panel.addView(message);Button retry=new Button(this);retry.setText("تلاش دوباره");retry.setOnClickListener(v->{root.removeView(panel);web.loadUrl(website);});panel.addView(retry);root.addView(panel,new FrameLayout.LayoutParams(-1,-1));});}
    @Override public void onBackPressed(){if(web!=null&&web.canGoBack())web.goBack();else super.onBackPressed();}
    @Override protected void onDestroy(){if(web!=null){web.stopLoading();web.destroy();}super.onDestroy();}
}
