package mars.mobile;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.util.Linkify;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;



import org.apache.http.HttpResponse;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.util.List;

public class Received_listviewActivity extends AppCompatActivity {
    public static SpannableStringBuilder htmlSpannable;
    public static TextView result=null;



    private final Handler mHideHandler = new Handler();
    private View mContentView;
    private final Runnable mHidePart2Runnable = new Runnable() {
        @SuppressLint("InlinedApi")
        @Override
        public void run() {

            mContentView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
        }
    };
    private String msgTag;
    private String p_messsage,weblink,imgUrl,subject;
    private URL url;
    private Bitmap imgBitmap;
    private ImageView img;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("메시지함");
        setContentView(R.layout.received_listview);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

        final DBHelper dbHelper = new DBHelper(getApplicationContext(), "MoneyBook.db", null, 1);

        Spanned spanned = Html.fromHtml(dbHelper.getResult());


        if (spanned instanceof SpannableStringBuilder) {

            htmlSpannable = (SpannableStringBuilder) spanned;
        } else {
            new SpannableStringBuilder(spanned);
        }

        result = (TextView) findViewById(R.id.result);
        result.setText(htmlSpannable);
        new ImageLoadTask(result.getContext(), htmlSpannable, result).execute();

        result.setLinksClickable(true);
        result.setAutoLinkMask(Linkify.ALL);

        if (getIntent().getExtras() != null) {
            onNewIntent(getIntent());
        }
              

    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        if (intent.getExtras() != null) {

              msgTag = intent.getExtras().getString("msgTag");
              p_messsage = intent.getExtras().getString("msg");
            subject= intent.getExtras().getString("title");
            weblink = intent.getExtras().getString("weblink");
            imgUrl = intent.getExtras().getString("imgUrl");

            String mode = intent.getExtras().getString("mode");
            String lCode = intent.getExtras().getString("lCode");
            Log.d("bb","message="+p_messsage);
            Log.d("bb","subject="+subject);
            Log.d("bb","weblink="+weblink);
            Log.d("bb","imgUrl="+imgUrl);
            try {
                p_messsage = URLDecoder.decode(p_messsage, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            if(TextUtils.isEmpty(subject)) subject = getResources().getString(R.string.app_name);
            if(imgUrl!=null)  new RetriveTweetTask().execute(imgUrl);

        }
    }

    private void MyCustomAlertDialog() {

        final Dialog MyDialog = new Dialog(Received_listviewActivity.this);
        MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        MyDialog.setContentView(R.layout.customdialog);
        MyDialog.setTitle("메시지");
        MyDialog.setCancelable(false);
        MyDialog.getWindow().getAttributes().windowAnimations = R.style.DialogSlide;

        Button hello = (Button)MyDialog.findViewById(R.id.hello);
        Button close = (Button)MyDialog.findViewById(R.id.close);
        TextView tv_subject = (TextView)MyDialog.findViewById(R.id.tv_subject);
        TextView tv_message = (TextView)MyDialog.findViewById(R.id.tv_message);
        TextView tv_weblink = (TextView)MyDialog.findViewById(R.id.tv_weblink);
        ImageView img = (ImageView)MyDialog.findViewById(R.id.img);
        tv_subject.setText(subject);
        tv_message.setText(p_messsage);
        tv_weblink.setText(weblink);
        if(imgUrl!=null)  img.setImageBitmap(imgBitmap);
        else img.setVisibility(View.GONE);
        hello.setEnabled(true);
        close.setEnabled(true);

        hello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(), "Hello, I'm Custom Alert Dialog", Toast.LENGTH_LONG).show();
                finish();
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.cancel();
                //finish();
            }
        });

        MyDialog.show();
    }

    public void go_img_url(View v){
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(imgUrl));
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {



         Intent i = new Intent(getApplicationContext(), MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if(!TextUtils.isEmpty(weblink)) {
            i.putExtra("param1", weblink);
            startActivity(i);
        }
        super.onDestroy();
    }

    // AsyncTask<Params,Progress,Result>
    private class RetriveTweetTask extends AsyncTask<String, Void, HttpResponse> {

        @Override
        protected HttpResponse doInBackground(String... urls) {



            try {
                url = new URL(imgUrl);
                URLConnection conn = url.openConnection();
                conn.connect();
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                imgBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HttpResponse result) {
            super.onPostExecute(result);
        }
    }


    public void updateIconBadgeCount(Context context, int count) {

        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", getLauncherClassName(context));
        intent.putExtra("badge_count", count);
        // send
        sendBroadcast(intent);
    }
    private String getLauncherClassName(Context context) {

        String result = "";
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(getPackageName());

        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
        if(resolveInfoList != null && resolveInfoList.size() > 0) {
            Log.d("bb","getpackagemanager");
            return resolveInfoList.get(0).activityInfo.name;
        }
        Log.d("bb","no getpackagemanager");
        return result;
    }


}
