package com.rn.s.baidumap.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.Animatable;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.widget.Button;
import android.text.Html;
import android.widget.TextView;
import android.widget.LinearLayout;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;

import androidx.annotation.RequiresApi;

import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.model.LatLng;
import com.facebook.common.references.CloseableReference;
import com.facebook.datasource.DataSource;
import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.drawee.drawable.ScalingUtils;
import com.facebook.drawee.generic.GenericDraweeHierarchy;
import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.DraweeHolder;
import com.facebook.imagepipeline.core.ImagePipeline;
import com.facebook.imagepipeline.image.CloseableImage;
import com.facebook.imagepipeline.image.CloseableStaticBitmap;
import com.facebook.imagepipeline.image.ImageInfo;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.facebook.react.views.view.ReactViewGroup;
import com.rn.s.baidumap.R;

import java.util.HashMap;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by sujialong on 2019/7/9.
 */

public class OverlayMarker extends ReactViewGroup implements OverlayView {

    private Marker marker;
    private List<String> title;
    private LatLng position;
    private String markerId;
    private BitmapDescriptor iconBitmapDescriptor;
    private Float rotate;
    private Float alpha;
    private Boolean flat;
    private Boolean perspective;
    private Boolean draggable;
    private Boolean active;
    private Boolean propActive;
    private int zIndex;
    private int infoWindowYOffset = 0;
    private int infoWindowMinHeight = 100;
    private int infoWindowMinWidth = 400;
    private int infoWindowTextSize = 16;
    private InfoWindow mInfoWindow;
    private BaiduMap mBaiduMap;
    private int iconHeight = 0;
    private float scale = 1;



    private DataSource<CloseableReference<CloseableImage>> dataSource;
    private volatile boolean loadingImage = false;
    private DraweeHolder<?> imageHolder;
    private final ControllerListener<ImageInfo> imageControllerListener =
            new BaseControllerListener<ImageInfo>() {
                @Override
                public void onFinalImageSet(
                        String id,
                        final ImageInfo imageInfo,
                        Animatable animatable) {
                    CloseableReference<CloseableImage> imageReference = null;
                    try {
                        imageReference = dataSource.getResult();
                        if (imageReference != null) {
                            CloseableImage image = imageReference.get();
                            if (image != null && image instanceof CloseableStaticBitmap) {
                                CloseableStaticBitmap closeableStaticBitmap = (CloseableStaticBitmap) image;
                                Bitmap bitmap = closeableStaticBitmap.getUnderlyingBitmap();
                                if (bitmap != null) {
                                    bitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
                                    iconBitmapDescriptor = BitmapDescriptorFactory.fromBitmap(bitmap);
                                    setIconHeight(iconBitmapDescriptor.getBitmap().getHeight());
                                }
                            }
                        }
                    } finally {
                        dataSource.close();
                        if (imageReference != null) {
                            CloseableReference.closeSafely(imageReference);
                        }
                        loadingImage = false;
                    }
                }
            };


    public OverlayMarker(Context context) {
        super(context);
        init();
    }

    protected void init() {
        GenericDraweeHierarchy genericDraweeHierarchy = new GenericDraweeHierarchyBuilder(getResources())
                .setActualImageScaleType(ScalingUtils.ScaleType.FIT_CENTER)
                .setFadeDuration(0)
                .build();
        imageHolder = DraweeHolder.create(genericDraweeHierarchy, getContext());
        imageHolder.onAttach();
    }

    public void setTitle(List<String> title) {
        this.title = title;
        if(mInfoWindow != null && active) {
            createInfoWindow();
        }
    }

    public void setScale(float scale) {
        this.scale = scale;
        if(marker != null) {
            marker.setScale(scale);
        }
    }

    public float getScale() {
        return this.scale;
    }

    public void setZIndex(int zIndex) {
        this.zIndex = zIndex;
    }

    public int getZIndex() {
        return this.zIndex;
    }

    public void setMarkerId(String markerId) {
        this.markerId = markerId;
    }

    public String getMarkerId() {
        return this.markerId;
    }

    public int getInfoWindowMinHeight() {
        return infoWindowMinHeight;
    }

    public void setInfoWindowMinHeight(int infoWindowMinHeight) {
        this.infoWindowMinHeight = infoWindowMinHeight;
        if(mInfoWindow != null && active) {
            createInfoWindow();
        }
    }

    public int getInfoWindowMinWidth() {
        return infoWindowMinWidth;
    }

    public void setInfoWindowMinWidth(int infoWindowMinWidth) {
        this.infoWindowMinWidth = infoWindowMinWidth;
        if(mInfoWindow != null && active) {
            createInfoWindow();
        }
    }

    public int getInfoWindowTextSize() {
        return infoWindowTextSize;
    }

    public void setInfoWindowTextSize(int infoWindowTextSize) {
        this.infoWindowTextSize = infoWindowTextSize;
        if(mInfoWindow != null && active) {
            createInfoWindow();
        }
    }

    public List<String> getTitle() {
        return this.title;
    }

    public void setPosition(double latitude, double longitude) {
        position = new LatLng(latitude, longitude);
        if(marker != null) {
            if(mInfoWindow != null && active) {
                createInfoWindow();
            }
            marker.setPosition(position);
        }
    }

    public LatLng getPosition() {
        return position;
    }

    public void setIcon(String uri) {
        if (uri == null) {
            iconBitmapDescriptor = null;
        } else if (uri.startsWith("http://") || uri.startsWith("https://") ||
                uri.startsWith("file://") || uri.startsWith("asset://")) {
            loadingImage = true;
            ImageRequest imageRequest = ImageRequestBuilder
                    .newBuilderWithSource(Uri.parse(uri))
                    .build();
            ImagePipeline imagePipeline = Fresco.getImagePipeline();
            dataSource = imagePipeline.fetchDecodedImage(imageRequest, this);
            DraweeController controller = Fresco.newDraweeControllerBuilder()
                    .setImageRequest(imageRequest)
                    .setControllerListener(imageControllerListener)
                    .setOldController(imageHolder.getController())
                    .build();
            imageHolder.setController(controller);
        } else {
            iconBitmapDescriptor = getBitmapDescriptorByName(uri);
        }
    }

    public BitmapDescriptor getIcon(int icon) {
        if (iconBitmapDescriptor != null) {
            return iconBitmapDescriptor;
        } else {
            return BitmapDescriptorFactory.fromResource(icon);
        }
    }

    public void setPerspective(boolean perspective) {
        this.perspective = perspective;
        if(marker != null) {
            marker.setPerspective(perspective);
        }
    }

    public boolean getPerspective() {
        return this.perspective;
    }

    public void setRotate(float rotat) {
        this.rotate = rotat;
        if(marker != null) {
            marker.setRotate(rotat);
        }
    }

    public float getRotate() {
        return this.rotate;
    }

    public void setAlpha(float alpha) {
        this.alpha = alpha;
        if(marker != null) {
            marker.setAlpha(alpha);
        }
    }

    public float getAlpha() {
        return this.alpha;
    }

    public void setFlat(boolean flat) {
        this.flat = flat;
        if(marker != null) {
            marker.setFlat(flat);
        }
    }

    public boolean getFlat() {
        return this.flat;
    }

    public void setDraggable(boolean draggable) {
        this.draggable = draggable;
        if(marker != null) {
            marker.setDraggable(draggable);
        }
    }

    public boolean getDraggable() {
        return this.draggable;
    }

    public void setActive(boolean active) {
        this.active = active;
        if(mInfoWindow != null) {
            if(active) {
                marker.hideInfoWindow();
            }else{
                marker.showInfoWindow(mInfoWindow);
            }
        }else{
            createInfoWindow();
        }
    }

    public boolean getActive() {
        return this.active;
    }

    public void setPropActive(boolean active) {
        this.propActive = active;
    }

    public boolean getPropActive() {
        return this.propActive;
    }

    public void setIconHeight(int iconHeight) {
        this.iconHeight = iconHeight;
    }
    public int getIconHeight() {
        return this.iconHeight;
    }

    public void setInfoWindowYOffset(int infoWindowYOffset) {
        this.infoWindowYOffset = infoWindowYOffset;
        if(mInfoWindow != null) {
            mInfoWindow.setYOffset(getInfoWindowYOffset());
        }
    }

    public int getInfoWindowYOffset() {
        int iconHeight = getIconHeight();
        this.infoWindowYOffset = this.infoWindowYOffset + -iconHeight;
        return this.infoWindowYOffset;
    }

    @Override
    public Object getOverlayView() {
        return marker;
    }

    @Override
    public void addTopMap(final BaiduMap baiduMap) {
        //不管图片是否加载成功，先会创建一个Marker显示默认图片，加载成功后替换默认图片
        if(marker == null) {
            addOverlay(baiduMap);
        }
        if (loadingImage) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(loadingImage) {
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException e) {
                            break;
                        }
                    }
                    marker.setScale(getScale());
                    marker.setIcon(getIcon(R.drawable.marker));
                    createInfoWindow();
                }
            }).start();
        }
    }

    private BitmapDescriptor scalBitMap(BitmapDescriptor bid, float ratio){
        Bitmap origin = bid.getBitmap();
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        // if (width>height){
        //     width=height;
        // }else {
        //     height=width;
        // }
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        return BitmapDescriptorFactory.fromBitmap(newBM);
    }

    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    public void addOverlay(BaiduMap baiduMap) {
        mBaiduMap = baiduMap;
        int[] markBits = new int[]{R.drawable.mark_1,R.drawable.mark_2,R.drawable.mark_3,R.drawable.mark_4,R.drawable.mark_5,R.drawable.mark_6,R.drawable.mark_7,R.drawable.mark_8,R.drawable.mark_9,R.drawable.mark_10};
        ArrayList<BitmapDescriptor> giflist = new ArrayList<BitmapDescriptor>();
        for (int icon:markBits) {
            //缩放图片
            giflist.add(scalBitMap(getIcon(icon),getScale()));
        }

        MarkerOptions markerOptions = new MarkerOptions()
                .alpha(getAlpha())
                .flat(getFlat())
                .perspective(getPerspective())
                .rotate(getRotate())
                .draggable(getDraggable())
                .position(getPosition())
                .zIndex(getZIndex())
                .scaleX(getScale())
                .yOffset(-15)
                .scaleY(getScale())
                .period(20)
                .icons(giflist);
        //在地图上展示包含帧动画的Marker
        marker= (Marker) (baiduMap.addOverlay(markerOptions));
        createInfoWindow();
    }

    public void createInfoWindow() {
        if(active && marker != null && getTitle().size() > 0) {
            LinearLayout linearLayout = new LinearLayout(getContext());
            LinearLayout linearLayout0 = new LinearLayout(getContext());
            LinearLayout linearLayout1 = new LinearLayout(getContext());
            LinearLayout linearLayout2 = new LinearLayout(getContext());
            LinearLayout linearLayout3 = new LinearLayout(getContext());
            LinearLayout linearLayout4 = new LinearLayout(getContext());
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            linearLayout0.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout1.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout2.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout3.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout4.setOrientation(LinearLayout.VERTICAL);
            if(getTitle().get(0).equals("warehouse") == true){
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setTextColor(Color.parseColor(getTitle().get(6)));
                    textView.setBackgroundColor(Color.parseColor("#ffffff"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    linearLayout.addView(textView);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#C1D8EA"));
                    textView.setTextColor(Color.parseColor("#666666"));
                    textView.setHeight( getTitle().get(2).equals("-") == true  ? 0 : 50);
                    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }

                  if(i==3){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#CFEBD2"));
                    textView.setTextColor(Color.parseColor("#666666"));
                    textView.setHeight( getTitle().get(3).equals("-") == true  ? 0 : 50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    linearLayout.addView(textView);
                  }

                  if(i==4){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }

                  if(i==5){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    textView.setHeight(50);
                    linearLayout.addView(textView);
                  }
              }
            }
            if(getTitle().get(0).equals("analyze") == true){
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setTextColor(Color.parseColor("#005798"));
                    textView.setBackgroundColor(Color.parseColor("#ffffff"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    textView.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    linearLayout0.addView(textView);
                    linearLayout.addView(linearLayout0);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#ffffff"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }

                  if(i==3){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#ffffff"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }

                  if(i==4){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#ffffff"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }
              }
            }

            if(getTitle().get(0).equals("transport") == true) {
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#2478F2"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }
              }
            }

            if(getTitle().get(0).equals("gas") == true) {
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#2478F2"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }
              }
            }

            if(getTitle().get(0).equals("stateGas") == true) {
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#F1F1F1"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout.addView(textView);
                  }
              }
            }

            if(getTitle().get(0).equals("state") == true) {
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    textView.setTextColor(Color.parseColor("#2478F2"));
                    textView.setHeight(50);
                    textView.setGravity(Gravity.CENTER);
                    linearLayout.addView(textView);
                  }
              }
            }
            if(getTitle().get(0).equals("material") == true) {
              for( int i = 1; i < getTitle().size(); i++ )
              {
                  if(i==1){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    textView.setTextColor(Color.parseColor("#333333"));
                    textView.setHeight(40);
                    textView.setWidth(300);
                    textView.setGravity(Gravity.CENTER_HORIZONTAL);
                    linearLayout.addView(textView);
                  }

                  if(i==2){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    textView.setTextColor(Color.parseColor("#666666"));
                    textView.setHeight(50);
                    textView.setWidth(150);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout1.addView(textView);
                  }

                  if(i==3){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#FFFFFF"));
                    textView.setTextColor(Color.parseColor("#2478F2"));
                    textView.setHeight(50);
                    textView.setWidth(150);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout1.addView(textView);
                    linearLayout.addView(linearLayout1);
                  }

                  if(i==4){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#C1D8EA"));
                    textView.setTextColor(Color.parseColor("#666666"));
                    textView.setHeight(50);
                    textView.setWidth(150);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout2.addView(textView);
                  }

                  if(i==5){
                    TextView textView = new TextView(getContext());
                    textView.setText(getTitle().get(i));
                    textView.setBackgroundColor(Color.parseColor("#C1D8EA"));
                    textView.setTextColor(Color.parseColor("#2478F2"));
                    textView.setHeight(50);
                    textView.setWidth(150);
                    textView.setGravity(Gravity.CENTER_VERTICAL);
                    linearLayout2.addView(textView);
                    linearLayout.addView(linearLayout2);
                  }
              }
            }
            mInfoWindow = new InfoWindow(BitmapDescriptorFactory.fromView(linearLayout),
              getPosition(), getInfoWindowYOffset(), new InfoWindow.OnInfoWindowClickListener(){
                @Override
                  public void onInfoWindowClick() {
                }
            });

            if(getTitle().get(0).equals("material") == true
                || getTitle().get(0).equals("analyze") == true
                || getTitle().get(0).equals("stateGas") == true
                || getTitle().get(0).equals("gas") == true
                || getTitle().get(0).equals("state") == true
                || getTitle().get(0).equals("transport") == true){
              marker.showInfoWindow(mInfoWindow);
            } else {
              marker.hideInfoWindow();
            }
        }
    }

    @Override
    public void remove() {
        if (marker != null) {
            marker.hideInfoWindow();
            marker.remove();
            marker = null;
            mInfoWindow = null;
        }
    }

    private BitmapDescriptor getBitmapDescriptorByName(String name) {
        return BitmapDescriptorFactory.fromResource(getDrawableResourceByName(name));
    }

    private int getDrawableResourceByName(String name) {
        return getResources().getIdentifier(
                name,
                "drawable",
                getContext().getPackageName());
    }
}
