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

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
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.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.util.ArrayList;
import java.util.HashMap;

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 BeforeImg_Fragment extends Fragment {
    private Handler handler, hdr;

    FragmentActivity fa;
    String wr_idx, wo_idx;

    RecyclerView list;
    ShootingRecyclerAdapter adapter;
    TextView noneImg;

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

    Bitmap bmp;

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

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

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

    public BeforeImg_Fragment() {
    }

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

        list = v.findViewById(R.id.list);
        noneImg = v.findViewById(R.id.noneImg);

        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);

        Get_Contents();

        return v;
    }

    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", "before");
        new ApiClient(data, "proc_worker_file", hdr);
    }

    void Set_Contents() {

    }

    void init_Handler() {
        hdr = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == -1) {
                    Toast.makeText(getContext(), msg.obj.toString().replace("\"", ""), Toast.LENGTH_SHORT).show();

                } else if (msg.what == 1) {
                    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());

                        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());
                            }

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

    private void init_Listener() {

    }

    View.OnClickListener itemClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int position = (int) v.getTag();
            RequestCreator picasso = Picasso.with(getContext()).load(items.get(position));
            try {
                picasso.into(new Target() {
                    @Override
                    public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                        bmp = bitmap;
                        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(bmp);
                        dialogBuilder.setView(view);
                        dialogBuilder.show();
                    }

                    @Override
                    public void onBitmapFailed(Drawable errorDrawable) {

                    }

                    @Override
                    public void onPrepareLoad(Drawable placeHolderDrawable) {

                    }
                });
            } catch (Exception e) {

            }
        }
    };
}
