package com.rehome.filesync;

import com.rehome.filesync.adapter.Q4UploadGridAdapter;
import com.rehome.filesync.contans.Contans;
import com.rehome.filesync.utils.GsonUtils;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.mbms.FileInfo;
import android.text.format.DateUtils;
import android.util.Log;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.rehome.filesync.bean.FileBean;
import com.rehome.filesync.utils.DownloadUtil;
import com.rehome.filesync.utils.HttpListener;
import com.rehome.filesync.utils.NoProgresshttpUtils;
import com.rehome.filesync.utils.NohttpUtils;
import com.rehome.filesync.weight.WaitDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yolanda.nohttp.Headers;
import com.yolanda.nohttp.NoHttp;
import com.yolanda.nohttp.RequestMethod;
import com.yolanda.nohttp.download.DownloadListener;
import com.yolanda.nohttp.download.DownloadQueue;
import com.yolanda.nohttp.download.DownloadRequest;
import com.yolanda.nohttp.rest.Request;
import com.yolanda.nohttp.rest.RequestQueue;
import com.yolanda.nohttp.rest.Response;
import com.zhy.autolayout.AutoLayoutActivity;

import org.litepal.crud.DataSupport;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okio.BufferedSource;
import okio.Okio;

public class MainActivity extends AutoLayoutActivity {
    public Context context;
    Button btnSync;
    Button btnSbcSync;
    Button btnAllSync;
    GridView gridView;
    private List<File> files;
    private static final int SD_REQUEST_CODE = 3;//请求码
    private ProgressDialog dialogFileLoading;
    private List<FileBean.DataBean> data;
    private List<FileBean.DataBean> dataMustDownload = new ArrayList<>();
    private Q4UploadGridAdapter gridAdapter;
    static int uploadSuccessCount = 0;
    static int mustDownloadCount = 0;

    private String syncType = "1";
    private WaitDialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AndPermission.with(this).runtime().permission(
                Permission.WRITE_EXTERNAL_STORAGE,
                Permission.READ_EXTERNAL_STORAGE
        ).onGranted(data -> {
        }).onDenied(data -> {
        }).start();
        context = this;
        dialog = new WaitDialog(context, "正在同步人脸库,请稍等 ...");
        dialog.setCancelable(false);

        btnSync = findViewById(R.id.btn_sync);
        btnSbcSync = findViewById(R.id.btn_sync_sbc);
        btnAllSync = findViewById(R.id.btn_sync_all);
        gridView = findViewById(R.id.gridView);
        data = new ArrayList<>();
        files = new ArrayList<>();

        dialogFileLoading = new ProgressDialog(this);
        dialogFileLoading.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialogFileLoading.setProgress(R.mipmap.ic_launcher);
        dialogFileLoading.setSecondaryProgress(R.mipmap.ic_launcher_round);//设置二级进度条的背景
        dialogFileLoading.setCancelable(true);// 设置是否可以通过点击Back键取消
        dialogFileLoading.setCanceledOnTouchOutside(false);// 设置在点击Dialog外是否取消Dialog进度条
        dialogFileLoading.setIcon(R.mipmap.ic_launcher);//
        dialogFileLoading.setMessage("正在同步人脸库,请稍等 ...");
        dialogFileLoading.setTitle("提示");
        dialogFileLoading.setMax(100);

        btnSync.setOnClickListener(view -> {
            syncType = "1";
            checkPermission(syncType);
        });

        btnSbcSync.setOnClickListener(view -> {
            syncType = "2";
            checkPermission(syncType);
        });

        btnAllSync.setOnClickListener(view -> {
            syncType = "3";
            checkPermission(syncType);
        });

        List<File> filesTemp = DownloadUtil.get().getImages("DCIM");
        if (filesTemp != null && filesTemp.size() > 0) {
            files.clear();
            files.addAll(filesTemp);
            showToast(String.valueOf(files.size()));
            //showToast(String.valueOf(files.get(0).getName()));
//            Collections.sort(files, new Comparator<File>() {
//
//                @Override
//                public int compare(File o1, File o2) {
//                    if (o1.lastModified() > o2.lastModified())
//                        return 1;
//                    else {
//                        return 0;
//                    }
//                }
//            });
        }
        gridAdapter = new Q4UploadGridAdapter(files, MainActivity.this);
        gridView.setAdapter(gridAdapter);
    }

    public void getFileList(String type) {
        uploadSuccessCount = 0;
        mustDownloadCount = 0;
        List<File> filesTemp = DownloadUtil.get().getImages("DCIM");
//        if (filesTemp != null && filesTemp.size() > 0) {
//            for (File file : filesTemp) {
//                if(file.isFile()){
//                    file.delete();
//                }
//            }
//            files.clear();
//            gridAdapter.notifyDataSetChanged();
//        }
        Log.i("app", Contans.IP + Contans.GET_FILE_LIST + "?type=" + type);
        Request<String> request = NoHttp.createStringRequest(Contans.IP + Contans.GET_FILE_LIST + "?type=" + type, RequestMethod.GET);
        //request.add("type",type);
        NohttpUtils.getInstance().add(this, 0, request, new HttpListener<String>() {

            @Override
            public void onSucceed(int what, Response<String> response) {

                Log.i("app", "----------------");
                Log.i("app", response.get());
                FileBean fileBean = GsonUtils.GsonToBean(response.get(), FileBean.class);
                if (fileBean != null && fileBean.getState() == 1) {
                    //Log.i("app", new Gson().toJson(fileBean));
                    List<FileBean.DataBean> dataTemp = fileBean.getData();
                    //Log.i("app",String.valueOf(dataTemp.size()));
                    if (dataTemp != null && dataTemp.size() > 0) {
                        Log.i("app", String.valueOf(dataTemp.size()));
                        showToast("需要同步的人脸库总共有" + String.valueOf(dataTemp.size() + "张图片"));
                        data.clear();
                        data.addAll(dataTemp);
                        dataMustDownload.clear();
                        for (FileBean.DataBean dataBean : data) {
                            boolean mustDownload = true;
                            for (File file : filesTemp) {
                                if (file.getName().equals(dataBean.getFileName())) {
                                    mustDownload = false;
                                    break;
                                }
                            }
                            if (mustDownload) {
                                mustDownloadCount++;
                                dataMustDownload.add(dataBean);
                            }
                        }
                        for (FileBean.DataBean dataBean : data) {
                            boolean mustDownload = true;
                            for (File file : filesTemp) {
                                if (file.getName().equals(dataBean.getFileName())) {
                                    mustDownload = false;
                                    break;
                                }
                            }
                            if (mustDownload) {
                                DownLoadImage(Contans.IP + Contans.GET_FILE + syncType + "/" + dataBean.getFileName());
                            }
                        }

                        //1
                        //https://www.zjtsp.com/FaceImages/1/龙小兵_男_180553.jpg
                        //2
                        //https://www.zjtsp.com/FaceImages/2/龙云辉_男_22457.jpg
                        //3
                        //https://www.zjtsp.com/FaceImages/3/宋雄武_男_C230043.jpg

//                        if (dataMustDownload.size() > 0) {
//                            DownLoadImageSync();
//                        }
                    }
                }
            }

            @Override
            public void onFailed(int what, Response<String> response) {

            }
        });
    }

    // 下载图片保存至手机
    public void DownLoadImage(String urlPath) {
        dialogFileLoading.show();
        Log.i("app",urlPath);
        DownloadUtil.get().download(urlPath, "DCIM", new DownloadUtil.OnDownloadListener() {
            @Override
            public void onDownloadSuccess(final String savePath, final String fileName) {

                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadSuccessCount++;
                        List<File> filesTemp = DownloadUtil.get().getImages("DCIM");
                        if (filesTemp != null && filesTemp.size() > 0) {
                            files.clear();
                            files.addAll(filesTemp);
                            if (uploadSuccessCount == mustDownloadCount) {
                                dialogFileLoading.dismiss();
                                gridAdapter.notifyDataSetChanged();
                            }
                        }
                    }
                });
            }

            @Override
            public void onDownloading(final int progress) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialogFileLoading.setMessage("正在同步人脸库，共"+String.valueOf(data.size())+"张图片，当前同步第"+String.valueOf(uploadSuccessCount)+"张，请稍等 ...");
                        dialogFileLoading.setProgress(progress);
                    }
                });
            }

            @Override
            public void onDownloadFailed() {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadSuccessCount++;
                        showToast("有部分人脸照片同步失败");
                        dialogFileLoading.dismiss();
                    }
                });
            }
        });
    }


    // 下载图片保存至手机
    public void DownLoadImageSync() {
        DownloadQueue queue = NoHttp.newDownloadQueue(); // 默认三个并发，此处可以传入并发数量。
        DownloadListener downloadListener = new DownloadListener() {
            @Override
            public void onDownloadError(int what, Exception exception) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        showToast("有部分人脸照片同步失败");
                        dialogFileLoading.dismiss();
                    }
                });
            }

            @Override
            public void onStart(int what, boolean resume, long preLenght, Headers header, long count) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 下载开始。
                        dialogFileLoading.show();
                    }
                });
            }

            @Override
            public void onProgress(int what, int progress, long fileCount) {
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialogFileLoading.setMessage("正在同步人脸库，共"+String.valueOf(dataMustDownload.size())+"张图片，当前同步第"+String.valueOf(uploadSuccessCount)+"张，请稍等 ...");
                        dialogFileLoading.setProgress(progress);
                    }
                });
            }

            @Override
            public void onFinish(int what, String filePath) {
                // 下载完成。
                MainActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        uploadSuccessCount++;
                        List<File> filesTemp = DownloadUtil.get().getImages("DCIM");
                        if (filesTemp != null && filesTemp.size() > 0) {
                            files.clear();
                            files.addAll(filesTemp);
                            dialogFileLoading.dismiss();
                            gridAdapter.notifyDataSetChanged();
                        }
                    }
                });
            }

            @Override
            public void onCancel(int what) {
                // 下载被取消或者暂停。
            }
        };
        DownloadUtil downloadUtil = DownloadUtil.get();
        try {
            // 储存下载文件的目录
            String savePath = downloadUtil.isExistDir("DCIM");
            Log.i("app",savePath);
            if (savePath != null) {
                for (FileBean.DataBean dataBean : dataMustDownload) {
                    String urlPath = Contans.IP + Contans.GET_FILE + dataBean.getFileName();
                    Log.i("app", Contans.IP + Contans.GET_FILE + syncType + "/" + dataBean.getFileName());
                    Log.i("app", dataBean.getFileName());
                    DownloadRequest request = NoHttp.createDownloadRequest(urlPath, RequestMethod.GET, savePath, dataBean.getFileName(), true, true);
                    // 发起下载请求：
                    queue.add(0, request, downloadListener);
                }
            } else {
                showToast("下载目录无权限访问");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void checkPermission(String type) {
        //动态权限申请
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //权限请求
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE}, SD_REQUEST_CODE);
        } else {
            Log.i("app", "-----------");
            Log.i("app", type);
            getFileList(type);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (SD_REQUEST_CODE == requestCode) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.i("app", "----------->");
                Log.i("app", syncType);
                getFileList(syncType);
            } else {
                //权限拒绝
                Toast.makeText(this, "权限拒绝,无法读取存储卡,请手动设置开启存储卡访问权限", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        context = null;
    }

    public void showToast(String text) {
        if (text != null && !text.trim().equals("")) {
            Toast.makeText(context, text, Toast.LENGTH_SHORT).show();
        }
    }
}