package com.maplehaze.adsdk.demo.utils;

import com.maplehaze.adsdk.nativ.NativeAdData;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class RandomAdUtil {
    public static NativeAdData getRandomAd(List<NativeAdData> adDataList){
        NativeAdData adData=null;
        if (adDataList!=null){
            int size=adDataList.size();
            int index=0;
            if(size==1){
                adData= adDataList.get(index);
            }else if(size>0){
                int min = 0;
                int max = size-1;
                Random random = new Random();
                index = min + random.nextInt(max - min + 1);
                adData= adDataList.get(index);
            }

            for (int i=0;i<adDataList.size();i++){
                if (i!=index){
                    NativeAdData item=adDataList.get(i);
                    if (item!=null){
                        item.destroy();
                    }
                }
            }
        }
        return adData;
    }

    public static List<NativeAdData>  getRandomAdList(List<NativeAdData> adDataList){
        if (adDataList!=null){
            Collections.shuffle(adDataList);
            if (adDataList.size()>=2){
                int size=1;
                if (adDataList.size()>size){
                    List<NativeAdData> releaseList=new ArrayList<>(adDataList.subList(size,adDataList.size()));
                    for (int i=0;i<releaseList.size();i++){
                        NativeAdData item=releaseList.get(i);
                        if (item!=null){
                            item.destroy();
                        }
                    }
                }
                return new ArrayList<>(adDataList.subList(0,size));
            }
        }

        return adDataList;
    }
}
