package kr.co.compcareworker.Fragment.Plan.Img;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

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

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.ortiz.touchview.TouchImageView;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.RequestCreator;
import com.squareup.picasso.Target;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import gun0912.tedimagepicker.builder.TedImagePicker;
import kr.co.compcareworker.Activity.FragmentActivity;
import kr.co.compcareworker.Data.ArrayItem;
import kr.co.compcareworker.Data.PlanDetail.WorkImg.WorkImgData;
import kr.co.compcareworker.R;
import kr.co.compcareworker.Util.Adapter.ShootingRecyclerAdapter;
import kr.co.compcareworker.Util.Api.ApiClient;
import kr.co.compcareworker.Util.Common;

@SuppressLint("ValidFragment")
public class Shooting_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;
    String wo_idx;
    String wr_idx;
    String type;
    ArrayList<Uri> imageUriArray;

    RecyclerView list;
    LinearLayout ll_act_shooting_add_picture;
    TextView tv_act_shooting_save;
    TextView noneImg;

    ProgressBar progress;
    ShootingRecyclerAdapter adapter;

    ArrayItem<WorkImgData> workImgDataArrayItem;
    ArrayList<String> items;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        fa = (FragmentActivity) getActivity();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        fa = null;
    }

    @SuppressLint("ValidFragment")
    public Shooting_Fragment(Handler handler, String wo_idx, String wr_idx, String type) {
        this.handler = handler;
        this.wo_idx = wo_idx;
        this.wr_idx = wr_idx;
        this.type = type;
    }

    public Shooting_Fragment() {
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.frag_shooting, container, false);

        list = v.findViewById(R.id.list);
        //ll_act_shooting_add_picture = v.findViewById(R.id.ll_act_shooting_add_picture);
        //tv_act_shooting_save = v.findViewById(R.id.tv_act_shooting_save);
        noneImg = v.findViewById(R.id.noneImg);
        progress = v.findViewById(R.id.progress);

        if (type.equals("view")) {
            ll_act_shooting_add_picture.setVisibility(View.GONE);
            tv_act_shooting_save.setVisibility(View.GONE);
        }

        Get_Contents();

        return v;
    }

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        Log.d("onActivityCreated", "onActivityCreated");
        init_Handler();
        init_Listener();

        int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3f, getResources().getDisplayMetrics());
        int itemHeight = (Common.getInstance().getWidth(getActivity())) - (list.getPaddingLeft() + list.getPaddingRight() - px * 6) / 3;
        adapter = new ShootingRecyclerAdapter(getContext(), hdr, itemHeight);
        list.setAdapter(adapter);

        imageUriArray = new ArrayList<>();
        int selectSize = adapter.getItemCount();
        if (selectSize < 15) {
            TedImagePicker.with(requireContext())
                    .startMultiImage(uriList -> {
                        imageUriArray.addAll(uriList);
                        ArrayList<String> arr = new ArrayList<>();
                        for (int i = 0; i < uriList.size(); i++) {
                            arr.add(uriList.get(i).toString());
                        }
                        int imageSize = adapter.getItemCount();
                        if (imageSize < 0) {
                            Toast.makeText(getContext(), "이미지를 추가하세요.", Toast.LENGTH_LONG).show();
                        } else {
                            progress.setVisibility(View.VISIBLE);
                            HashMap<String, String> data = new HashMap<>();
                            data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
                            data.put("wo_idx", wo_idx);
                            data.put("wr_idx", wr_idx);
                            data.put("mb_id", Common.getInstance().getPref(getContext(), "id"));
                            new ApiClient(data, "proc_work_photo_write", imageUriArray, hdr);
                        }
                        adapter.addMoreItem(arr);
                    });

//            TedBottomPicker tedBottomPicker = new TedBottomPicker.Builder(getContext()).setImageProvider(new TedBottomPicker.ImageProvider() {
//                @Override
//                public void onProvideImage(ImageView imageView, Uri imageUri) {
//                    Glide.with(getContext()).load(imageUri).apply(RequestOptions.centerCropTransform()).into(imageView);
//                }
//            }).setOnMultiImageSelectedListener(new TedBottomPicker.OnMultiImageSelectedListener() {
//                @Override
//                public void onImagesSelected(ArrayList<Uri> uriList) {
//                    imageUriArray.addAll(uriList);
//                    ArrayList<String> arr = new ArrayList<>();
//                    for (int i = 0; i < uriList.size(); i++) {
//                        arr.add(uriList.get(i).toString());
//                    }
//                    int imageSize = adapter.getItemCount();
//                    if (imageSize < 0) {
//                        Toast.makeText(getContext(), "이미지를 추가하세요.", Toast.LENGTH_LONG).show();
//                    } else {
//                        progress.setVisibility(View.VISIBLE);
//                        HashMap<String, String> data = new HashMap<>();
//                        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
//                        data.put("wo_idx", wo_idx);
//                        data.put("wr_idx", wr_idx);
//                        data.put("mb_id", Common.getInstance().getPref(getContext(), "id"));
//                        new ApiClient(data, "proc_work_photo_write", imageUriArray, hdr);
//                    }
//                    adapter.addMoreItem(arr);
//                }
//            })
//                    .setCompleteButtonText("저장")
//                    .setPeekHeight(2400)
//                    .setPreviewMaxCount(1000).setSelectMaxCount(15 - selectSize).create();
//            tedBottomPicker.show(getActivity().getSupportFragmentManager());
        } else {
            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
            dialogBuilder.setTitle("콤프케어 작업자");
            dialogBuilder.setMessage("사진은 최대 15개까지 등록가능합니다.");
            dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int i) {
                    Log.e("사진 저장", "Shooting_Fragment.java");
                    dialog.dismiss();
                }
            });
            dialogBuilder.show();
        }
    }


    void Get_Contents() {
        HashMap<String, String> data = new HashMap<>();
        data.put("ag_idx", fa.userItem.getArrayitem().getAgIdx());
        data.put("wr_idx", wr_idx);
        data.put("wo_idx", wo_idx);
        data.put("file_type", "after");
        new ApiClient(data, "proc_worker_file", hdr);
    }

    void Set_Contents() {

    }

    public void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                Log.e("hdr", hdr.toString());
                Log.e("msg", msg.toString());


                String url = msg.getData().getString("url");
                if (url.equals("proc_worker_file")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    workImgDataArrayItem = new Gson().fromJson(result_item, new TypeToken<ArrayItem<WorkImgData>>() {
                    }.getType());

                    imageUriArray = new ArrayList<>();
                    if (workImgDataArrayItem.isSuccess()) {
                        noneImg.setVisibility(View.GONE);
                        list.setVisibility(View.VISIBLE);
                        items = new ArrayList<>();

                        for (int i = 0; i < workImgDataArrayItem.getArrayitem().size(); i++) {
                            items.add(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                            new ImageDownload(workImgDataArrayItem.getArrayitem().get(i).getPfiFilename().split("\\.")[0])
                                    .execute(workImgDataArrayItem.getArrayitem().get(i).getUrl());
                        }

                        adapter.addItem(items);
                        adapter.itemClick = itemClickListener;
                    } else {
                        noneImg.setVisibility(View.VISIBLE);
                        list.setVisibility(View.GONE);
                    }

                    progress.setVisibility(View.GONE);
                } else if (url.equals("proc_work_photo_write")) {
                    JsonElement element = new JsonParser().parse(msg.obj.toString());
                    JsonObject result_item = element.getAsJsonObject();
                    if (result_item.get("resultItem").getAsJsonObject().get("result").getAsString().equals("Y")) {
                        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
                        Toast.makeText(getContext(), "저장되었습니다.", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();
                        getActivity().setResult(Activity.RESULT_OK, intent);
                        getActivity().finish();
                    } else {
                        Toast.makeText(getContext(), result_item.get("resultItem").getAsJsonObject().get("message").getAsString(), Toast.LENGTH_LONG).show();
                    }

                    progress.setVisibility(View.GONE);
                }
            }
        };
    }

    private void init_Listener() {

        Log.e("액티비티 종료", "finish()");
    }


    View.OnClickListener itemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();

            if (type.equals("view")) {
                RequestCreator picasso = Picasso.with(getContext()).load(items.get(position));
                try {
                    picasso.into(new Target() {
                        @Override
                        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                            View view = getLayoutInflater().inflate(R.layout.dlg_image, null);
                            TouchImageView iv = view.findViewById(R.id.imageview);
                            iv.setImageBitmap(bitmap);
                            dialogBuilder.setView(view);
                            dialogBuilder.show();
                        }

                        @Override
                        public void onBitmapFailed(Drawable errorDrawable) {

                        }

                        @Override
                        public void onPrepareLoad(Drawable placeHolderDrawable) {

                        }
                    });
                } catch (Exception e) {

                }
            } else {
                AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(getContext());
                dialogBuilder.setTitle("콤프케어 작업자");
                dialogBuilder.setMessage("삭제하시겠습니까?");
                dialogBuilder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int i) {
                        int size = adapter.dataImgNo.size();
                        adapter.removeItem(position);
                        if (imageUriArray.size() > 0) {
                            imageUriArray.remove(position - size);
                        }
                        dialog.dismiss();
                    }
                });
                dialogBuilder.show();
            }
        }
    };

    private class ImageDownload extends AsyncTask<String, Void, Void> {
        /**
         * 파일명
         */
        private String fileName;
        /**
         * 저장할 폴더
         */
        private final String SAVE_FOLDER = "/CompcareWorker";

        public ImageDownload(String fileName) {
            this.fileName = fileName.substring(8, fileName.length() - 1);
        }

        @Override
        protected Void doInBackground(String... params) {
            //다운로드 경로를 지정
            //String savePath = Environment.getExternalStorageDirectory().getAbsolutePath() + SAVE_FOLDER;
            String savePath = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER;
            File dir = new File(savePath);
            //상위 디렉토리가 존재하지 않을 경우 생성
            if (!dir.exists()) {
                dir.mkdirs();
            }
            //웹 서버 쪽 파일이 있는 경로
            String fileUrl = params[0];
            //다운로드 폴더에 동일한 파일명이 존재하는지 확인
            if (new File(savePath + "/" + fileName).exists() == false) {

            } else {

            }

            String localPath = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER + "/" + fileName + ".jpg";
            try {
                URL imgUrl = new URL(fileUrl);
                //서버와 접속하는 클라이언트 객체 생성
                HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                int len = conn.getContentLength();
                byte[] tmpByte = new byte[len];
                //입력 스트림을 구한다
                InputStream is = conn.getInputStream();
                File file = new File(localPath);
                file.createNewFile();

                //파일 저장 스트림 생성
                FileOutputStream fos = new FileOutputStream(file);
                int read;
                //입력 스트림을 파일로 저장
                for (; ; ) {
                    read = is.read(tmpByte);
                    if (read <= 0) {
                        break;
                    }
                    fos.write(tmpByte, 0, read); //file 생성
                }
                is.close();
                fos.close();
                conn.disconnect();
            } catch (Exception e) {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) {
            super.onPostExecute(result);
            String targetDir = Environment.getExternalStorageDirectory() + "/DCIM" + SAVE_FOLDER;
            File file = new File(targetDir + "/" + fileName + ".jpg");
            imageUriArray.add(Uri.fromFile(file));
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Common.getInstance().setDirEmpty(getContext(), "/CompcareWorker");
    }
}
