package com.amsal.ta.ui.dashboard;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amsal.ta.R;
import com.amsal.ta.ResultActivity;
import com.amsal.ta.adapter.AppAdapter;
import com.amsal.ta.model.AppInfo;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import cz.msebera.android.httpclient.Header;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class DashboardFragment extends Fragment {

    RecyclerView gridView;
    private ProgressBar progressBar;
    private ConstraintLayout scan;
    boolean mIncludeSystemApps;
    private Button btnScan;
    private ImageView clear;
    private BottomNavigationView bottomNavigationView;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_dashboard, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {

        scan = getActivity().findViewById(R.id.scan_layout);
        gridView = getView().findViewById(R.id.griview);
        gridView.setHasFixedSize(true);
        btnScan = getActivity().findViewById(R.id.btn_scan);
        bottomNavigationView = getActivity().findViewById(R.id.nav_view);
        clear = getActivity().findViewById(R.id.clear);
        progressBar = getActivity().findViewById(R.id.progressBar);
        progressBar.setVisibility(View.INVISIBLE);


        List<AppInfo> apps = new ArrayList<>();
        PackageManager packageManager = getActivity().getPackageManager();
        List<ApplicationInfo> infos = packageManager.getInstalledApplications(PackageManager.GET_META_DATA);

        for (ApplicationInfo info : infos) {
            if (!mIncludeSystemApps && (info.flags & ApplicationInfo.FLAG_SYSTEM) == 1) {
                continue;
            }
            AppInfo app = new AppInfo();
            app.info = info;
            app.label = (String) info.loadLabel(packageManager);
            apps.add(app);
        }

        //sort the data

        Collections.sort(apps, new DNComparator());
        gridView.setLayoutManager(new GridLayoutManager(getContext(), 4));
        final AppAdapter adapter = new AppAdapter(getActivity(), apps);
        gridView.setAdapter(adapter);

        adapter.setOnItemClickCallback(new AppAdapter.OnItemClickCallback() {
            @Override
            public void onItemClicked(AppInfo data) {
                int count = adapter.getSelected();
                if (count > 0) {
                    bottomNavigationView.setVisibility(View.INVISIBLE);
                    scan.setVisibility(View.VISIBLE);
                    btnScan.setText("SCAN(" + count + ")");
                } else {
                    scan.setVisibility(View.INVISIBLE);
                    bottomNavigationView.setVisibility(View.VISIBLE);
                }
//                Toast.makeText(getActivity(), data.label, Toast.LENGTH_LONG).show();
            }
        });

        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adapter.clearSelected();
                gridView.setAdapter(adapter);
                scan.setVisibility(View.INVISIBLE);
                bottomNavigationView.setVisibility(View.VISIBLE);
            }
        });

        btnScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent resultIntent = new Intent(getContext(), ResultActivity.class);
                resultIntent.putParcelableArrayListExtra(ResultActivity.EXTRA_APP, adapter.getSelectedApk());
                startActivity(resultIntent);
            }
        });

    }

    private class DNComparator implements Comparator<AppInfo> {

        @Override
        public int compare(AppInfo aa, AppInfo ab) {
            CharSequence sa = aa.label;
            CharSequence sb = ab.label;
            if (sa == null) {
                sa = aa.info.packageName;
            }
            if (sb == null) {
                sb = ab.info.packageName;
            }
            return Collator.getInstance().compare(sa.toString(), sb.toString());
        }
    }

//    private void scanApk(List<AppInfo> apps){
//        progressBar.setVisibility(View.VISIBLE);
//
//        AsyncHttpClient client = new AsyncHttpClient();
//        String url = "https://tugasakhir03.herokuapp.com/upload/";
//
//        RequestParams params = new RequestParams();
//        try {
//            for(int i = 0 ; i < apps.size(); i++){
//                File apkFile = new File(apps.get(i).info.publicSourceDir);
//                String packageName = apps.get(i).info.packageName;
//                if (apkFile.isFile()) {
////                    installedApkFilePaths.put(packageName, apkFile.getAbsolutePath());
////                    Toast.makeText(getActivity(), apkFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
//                      params.put("file", apkFile.getAbsoluteFile());
//                      Log.d("horas" ,apkFile.getAbsoluteFile().getName());
//                }
//            }
////            params.put("file", myFile);
//        } catch(Exception e) {
//            Log.d("horas" , "gagal");
//        }
//        client.put(getActivity(), url, params, new AsyncHttpResponseHandler() {
//            @Override
//            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
//                Log.d("horas" , "mantap");
//                progressBar.setVisibility(View.INVISIBLE);
//            }
//
//            @Override
//            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
//                Log.d("horas" , "ancor");
//                Log.e("horas    ", "onFailure: ERROR > " + error.getMessage());
//            }
//
//        });


//    }

//    private void scanApk(List<AppInfo> apps) {
//        ArrayList<JSONObject> resultApk = new ArrayList<JSONObject>();
//        ArrayList<String> hasil = new ArrayList<String>();
//        List<AppInfo> status = new ArrayList<AppInfo>();
//        String url = "https://tugasakhir03.herokuapp.com/upload/";
////        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);
////
////        }).build();
////
////        for (int i = 0; i < apps.size(); i++) {
////            File apkFile = new File(apps.get(i).info.publicSourceDir);
////            String packageName = apps.get(i).info.packageName;
////            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();
////                Log.d("horas", apkFile.getAbsoluteFile().getName());
////
////                Request request = new Request.Builder()
////                        .url(url)
//////                .header("Prediction-Key", "42b03f551d0a439785a7f601b92a18fb")
//////                .header("Content-Type", "application/octet-stream")
////                        .post(requestBody)
////                        .build();
////
////                fileUploadClient.newCall(request).enqueue(new Callback() {
////                    @Override
////                    public void onFailure(@NotNull Call call, @NotNull IOException e) {
////                        Log.e("horas", "onFailure: ERROR > " + e.getMessage());
////                        return;
//////                loading.dismiss();
////                    }
////
////                    @Override
////                    public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
////                        if (response.isSuccessful()) {
////                            Log.i("horas", "onResponse: BERHASIL");
////                            try {
////                                JSONObject jsonObject = new JSONObject(response.body().string());
////                                String status = jsonObject.getString("status");
////                                String malware_name = jsonObject.getString("malware_name");
//////                        hasil.add(status);
//////                        hasil.add(malware_name);
//////                        hasil.add("Berhasil");
//////                        Intent uploadIntent = new Intent(UploadActivity.this, UploadResultActivity.class);
//////                        Toast.makeText(getApplicationContext() , jsonObject.toString(), Toast.LENGTH_LONG).show();
//////                        for (int i = 0; i < jsonObject.getJSONArray("status").length(); i++) {
//////                            probability = jsonObject.getJSONArray("predictions").getJSONObject(0).getString("probability");
//////                            tagName = jsonObject.getJSONArray("predictions").getJSONObject(0).getString("tagName");
//////                            Log.i("debug", "responseBody: " + tagName + " = " + probability);
//////                        }
//////                        uploadIntent.putExtra("AppInfo" , app);
////                                Log.i("horas", status);
//////                        loading.dismiss();
//////                        getDataHamaResources(tagName);
//////                        runOnUiThread(() -> getDataTanahResources(tagName));
//////                        runOnUiThread(() -> showToast(tagName));
////                            } catch (JSONException | IOException e) {
////                                e.printStackTrace();
////                            }
////                        } else {
////                            Log.i("horas", "onResponse: GAGAL");
//////                    loading.dismiss();
////                        }
////                    }
////                });
////            }else{
////
////            }
////        }
//
//        JSONObject json = new JSONObject();
//        JSONArray array = new JSONArray();
//        JSONObject item = new JSONObject();
//
//        //ini sementara, nanti akan dipindahkan jika server sudah oke
//        try {
//            json.put("nama_apk", "horas");
//
//            item.put("status", "Tidak Berbahaya");
//            item.put("malware_name", "-");
//
//            array.put(item);
//
//            json.put("response", array);
//            Log.d("horas", json.getJSONArray("response").getJSONObject(0).getString("status"));
//        }catch (Exception e){}
//
//        resultApk.add(json);
//        status.add(apps.get(0));
//
//
//    }

}