package com.android.chmo.ui.view;


import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.util.Log;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.android.chmo.utils.XUtilsImage;

import java.util.ArrayList;
import java.util.List;


public class ImageGroupView extends LinearLayout{
    private List<String> imgList = new ArrayList<>();

    public ImageGroupView(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(LinearLayout.HORIZONTAL);

        ViewTreeObserver vto = getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onGlobalLayout() {
                int height = getHeight();
                int width = getWidth();
                getViewTreeObserver().removeOnGlobalLayoutListener(this);

                fillView(width,height);
            }
        });
    }

    public void setImageList(List<String> imgs) {
        imgList = imgs;
        int height = getHeight();
        int width = getWidth();
        if(height != 0 && width != 0) {
            fillView(width,height);
        }
    }

    private void fillView(int width, int height){
        removeAllViews();
        if (imgList.isEmpty()){
            return;
        }
        if(imgList.size() == 1) {
            addView(getImage(0,width,height));
        }else if(imgList.size() == 2){
            addView(getImage(0,width/2,height));
            addView(getImage(1,width/2,height));
        }else if(imgList.size() == 3){
            addView(getImage(0,width/2,height));
            LinearLayout layout = new LinearLayout(getContext());
            layout.setOrientation(LinearLayout.VERTICAL);
            addView(layout);
            layout.addView(getImage(1,width/2,height/2));
            layout.addView(getImage(2,width/2,height/2));
        }else {
            LinearLayout layout1 = new LinearLayout(getContext());
            layout1.setOrientation(LinearLayout.VERTICAL);
            addView(layout1);
            LinearLayout layout2 = new LinearLayout(getContext());
            layout2.setOrientation(LinearLayout.VERTICAL);
            addView(layout2);
            layout1.addView(getImage(0,width/2,height/2));
            layout1.addView(getImage(1,width/2,height/2));
            layout2.addView(getImage(2,width/2,height/2));
            layout2.addView(getImage(3,width/2,height/2));
        }
    }

    private ImageView getImage(int pos, int width, int height) {
        ImageView image = new ImageView(getContext());
        image.setLayoutParams(new LayoutParams(width,height));
        XUtilsImage.displayWithSize(image, imgList.get(pos),width,height);
        return image;
    }
}
