package com.secspace.lib.common.function;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;

import com.secspace.lib.common.R;
import com.secspace.lib.common.utils.IntentUtil;
import com.secspace.lib.common.utils.Prefs;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class PrivacyPolicyDialog implements DialogInterface.OnDismissListener, View.OnClickListener {
    private static final String TAG = "PrivacyPolicyDialog";
    private Activity mActivity;
    private android.app.AlertDialog mDialog;
    private TextView permissionText;
    private TextView statementText;
    private TextView statementText1;
    private Button btnExit;
    private Button btnAccept;
    private View layout;

    public PrivacyPolicyDialog(Activity activity) {
        this.mActivity = activity;
    }

    public PrivacyPolicyDialog show() {
        if (mDialog == null) {
            initView();
            android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mActivity);
            mDialog = builder.create();
            mDialog.setCancelable(false);
            Window window = mDialog.getWindow();
            window.setBackgroundDrawableResource(R.drawable.dialog_corner_bg);

            String filename = "html/permission_statement.html";
            String content = getStringFromHtmlFile(mActivity, filename);
            permissionText.setText(Html.fromHtml(content));

            btnExit.setOnClickListener(this);
            btnAccept.setOnClickListener(this);
            statementText.setMovementMethod(LinkMovementMethod.getInstance());
            statementText1.setMovementMethod(LinkMovementMethod.getInstance());
            CharSequence text = statementText.getText();
            CharSequence text1 = statementText1.getText();
            setText(statementText, text);
            setText(statementText1, text1);

            mDialog.setView(layout);
            mDialog.show();
        }
        if (!mDialog.isShowing()) {
            mDialog.show();
        }
        return this;
    }

    private void initView() {
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        layout = inflater.inflate(R.layout.privacypolicydialog_layout, null);
        permissionText = layout.findViewById(R.id.content_permissions);
        statementText = layout.findViewById(R.id.read_statement);
        statementText1 = layout.findViewById(R.id.read_statement1);
        btnExit = layout.findViewById(R.id.btn_exit);
        btnAccept = layout.findViewById(R.id.btn_accept);

    }

    public void setText(TextView view, CharSequence text) {
        if (text instanceof Spannable) {
            int end = text.length();
            Spannable sp = (Spannable) text;
            URLSpan[] urls = sp.getSpans(0, end, URLSpan.class);
            SpannableStringBuilder style = new SpannableStringBuilder(text);
            style.clearSpans();
            for (URLSpan url : urls) {
                MyURLSpan myURLSpan = new MyURLSpan();
                style.setSpan(myURLSpan, sp.getSpanStart(url), sp.getSpanEnd(url), Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
            }
            view.setText(style);
        }
    }

    public void dismiss() {
        if (mDialog != null && mDialog.isShowing())
            mDialog.dismiss();
    }

    @Override
    public void onDismiss(DialogInterface dialog) {
        mActivity = null;
        mDialog = null;
    }

    public static String getStringFromHtmlFile(Context context, String filePath) {
        String result = "";
        if (null == context || null == filePath) {
            return result;
        }

        InputStream stream = null;
        BufferedReader reader = null;
        InputStreamReader streamReader = null;
        try {
            stream = context.getAssets().open(filePath);
            streamReader = new InputStreamReader(stream, "utf-8");
            reader = new BufferedReader(streamReader);
            StringBuilder builder = new StringBuilder();
            String line = null;

            boolean readCurrentLine = true;
            while ((line = reader.readLine()) != null) {
                if (line.contains("<style")) {
                    readCurrentLine = false;
                } else if (line.contains("</style")) {
                    readCurrentLine = true;
                }
                if (readCurrentLine) {
                    builder.append(line).append("\n");
                }
            }
            result = builder.toString();
        } catch (FileNotFoundException ex) {
            Log.e(TAG, ex.getMessage());
        } catch (Exception ex) {
            Log.e(TAG, ex.getMessage());
        } finally {
            if (null != reader) {
                try {
                    reader.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.getMessage());
                }
            }
            if (null != streamReader) {
                try {
                    streamReader.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.getMessage());
                }
            }
            if (null != stream) {
                try {
                    stream.close();
                } catch (IOException ex) {
                    Log.e(TAG, ex.getMessage());
                }
            }
        }
        return result;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.btn_exit) {
            mActivity.finish();
        } else if (v.getId() == R.id.btn_accept) {
            Prefs.setPrivacyPolicyState(mActivity, true);
            IntentUtil.startEduLauncher(mActivity);
            dismiss();
            mActivity.finish();
        }
    }

    private class MyURLSpan extends ClickableSpan {
        @Override
        public void onClick(View view) {
            view.setBackgroundColor(Color.parseColor("#00000000"));
            Intent intent = null;
            try {
                intent = new Intent(mActivity, Class.forName("com.android.launcher3.function.setting.PrivacyPolicyActivity"));
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            mActivity.startActivity(intent);
        }
    }
}
