package com.amsal.ta;

import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.amsal.ta.adapter.ResultAdapter;
import com.amsal.ta.model.AppInfo;
import com.amsal.ta.model.AppResult;

import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class ResultActivity extends AppCompatActivity implements MyAsyncCallback {
    public static final String EXTRA_APP = "extra_app";
    private RecyclerView rvResult;
    private RelativeLayout errorLayout;
    private ImageView errorImg;
    private Button exit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        errorLayout = findViewById(R.id.error_layout);
        exit = findViewById(R.id.back_btn);
        errorImg = findViewById(R.id.error_img);
        ArrayList<AppInfo> apps = getIntent().getParcelableArrayListExtra(EXTRA_APP);
        errorLayout.setVisibility(View.GONE);
        rvResult = findViewById(R.id.rv_result);
        rvResult.setHasFixedSize(true);

        Async async = new Async(this);
        async.execute(apps);

    }

    @Override
    public void onPreExecute() {

    }

    @Override
    public void onPostExecute(ArrayList<AppResult> list) {
        if (list.size() != 0) {
            rvResult.setLayoutManager(new LinearLayoutManager(this));
            ResultAdapter resultAdapter = new ResultAdapter(this, list);
            rvResult.setAdapter(resultAdapter);
        } else {
            if (errorLayout.getVisibility() == View.GONE) {
                errorLayout.setVisibility(View.VISIBLE);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent moveIntent = new Intent(ResultActivity.this, IntroActivity.class);
                        startActivity(moveIntent);
                        finish();
                    }
                });
                errorImg.setImageResource(R.drawable.error);
            }
        }

    }

    private class Async extends AsyncTask<ArrayList<AppInfo>, Void, ArrayList<AppResult>> {
        static final String LOG_ASYNC = "DemoAsync";
        WeakReference<MyAsyncCallback> myListener;
        ProgressDialog mProgressDialog;

        Async(MyAsyncCallback myListener) {
            this.myListener = new WeakReference<>(myListener);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.d(LOG_ASYNC, "status : onPreExecute");
            mProgressDialog = new ProgressDialog(ResultActivity.this);
            // Set your ProgressBar Title
            mProgressDialog.setTitle("Scanning Apps");
            mProgressDialog.setIcon(R.drawable.ic_file_upload_black_24dp);
            // Set your ProgressBar Message
            mProgressDialog.setMessage("Still Scanning Your Apps, Please Wait!");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            // Show ProgressBar
            mProgressDialog.setCancelable(false);
//            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.show();

            MyAsyncCallback myListener = this.myListener.get();
            if (myListener != null) {
                myListener.onPreExecute();
            }
        }

        @Override
        protected ArrayList<AppResult> doInBackground(ArrayList<AppInfo>... apps) {
            Log.d(LOG_ASYNC, "status : doInBackground");
            String url = "https://tad3ti03.xyz/upload/";
            return Scan(apps[0], url);
        }

        @Override
        protected void onPostExecute(ArrayList<AppResult> result) {
            super.onPostExecute(result);
            mProgressDialog.dismiss();
            Log.d(LOG_ASYNC, "status : onPostExecute");
            MyAsyncCallback myListener = this.myListener.get();
            if (myListener != null) {
                myListener.onPostExecute(result);
            }
        }
    }

    public static ArrayList<AppResult> Scan(ArrayList<AppInfo> apps, String url) {

        String fileName;
        ArrayList<AppResult> list = new ArrayList<>();


        OkHttpClient fileUploadClient = new OkHttpClient.Builder().addNetworkInterceptor(chain -> {
            Request originalRequest = chain.request();

            if (originalRequest.body() == null) {
                return chain.proceed(originalRequest);
            }
            Request progressRequest = originalRequest.newBuilder()
                    .build();

            return chain.proceed(progressRequest);

        }).connectTimeout(30000, TimeUnit.SECONDS)
                .writeTimeout(30000, TimeUnit.SECONDS)
                .readTimeout(30000, TimeUnit.SECONDS)
                .build();

        for (int i = 0; i < apps.size(); i++) {
            File apkFile = new File(apps.get(i).info.publicSourceDir);
            if (apkFile.isFile()) {
                fileName = apps.get(i).info.publicSourceDir;
                RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM).addFormDataPart("file", fileName, RequestBody.create(apkFile, MediaType.parse("application/*"))).build();
                Request request = new Request.Builder().url(url).post(requestBody).build();

                try {
                    Response response = fileUploadClient.newCall(request).execute();
                    if (response.isSuccessful()) {
                        Log.i("horas", "onResponse: BERHASIL");
                        try {
                            JSONObject jsonObject = new JSONObject(response.body().string());

                            AppResult sucsess = new AppResult();
                            sucsess.app = apps.get(i);
                            sucsess.apkName = jsonObject.getString("nama_apk");
                            sucsess.malware = jsonObject.getString("malware_name");
                            sucsess.status = jsonObject.getString("status");
                            sucsess.detail = jsonObject.getString("detail");
                            list.add(sucsess);
                            Log.d("horas", list.get(i).detail);
                        } catch (Exception e) {
                        }

                    } else {
                        Log.i("horas", "onResponse: GAGAL");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return list;
    }

}

interface MyAsyncCallback {
    void onPreExecute();

    void onPostExecute(ArrayList<AppResult> list);
}
