package org.ccalm.weather;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

import org.springframework.http.CacheControl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import tctable.Tools;

import javax.servlet.http.HttpServletResponse;
/*
 * Server buffer for map tiles.
*/

@Controller
public class GeoTIFFList {
	
	//---------------------------------------------------------------------------	
	public String dayofyear2date( int day ) {
		//int day=Integer.parseInt(sDay)+1;
		Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_YEAR, day);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String result=format.format(calendar.getTime());
		return result;
	}
	//---------------------------------------------------------------------------
	public int[] setUnique(int[] array) {
		int[] noDuplicates = IntStream.of(array).distinct().toArray();
		return noDuplicates;
	}
	//---------------------------------------------------------------------------
	public int[] toIntarray(Object[] obj){
		int length = obj.length;
		int intArray[] = new int[length];
		for(int i=0; i<length; i++){
			intArray[i] = (int) obj[i];
		}
		return intArray;
     }
	//---------------------------------------------------------------------------
	//List GeoTIFF files
	@CrossOrigin
    @RequestMapping(value = "/geodatalist/GeoTIFF",method = RequestMethod.GET,produces = "text/html;charset=UTF-8")
    @ResponseBody
	public Object geoTIFFData(HttpServletResponse response,@RequestParam(required=true,name="fn") String fn) {
		String headerValue = CacheControl.maxAge(60, TimeUnit.SECONDS).getHeaderValue();
		response.addHeader("Cache-Control", headerValue);

		String NDVIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDVI";
		String NDWIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDWI";
		String NDSIPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/NDSI";
		String SMAPPath="/opt/tomcat/geoserver/ROOT/data/GeoTIFF/SMAP";
		String osName=System.getProperty("os.name");
		if(osName.indexOf("Windows")>=0){
			NDVIPath="O:\\temp\\CCALM\\NDVI";
			NDWIPath="O:\\temp\\CCALM\\NDVI";
			NDSIPath="O:\\temp\\CCALM\\NDVI";
			SMAPPath="O:\\temp\\CCALM\\SMAP";
		}
		String result="";

    	if(fn.equals("ndvi_list")) {
    		List<Integer> arrlist = new ArrayList<Integer>();
    		
            String[] names;
            File f = new File(NDVIPath);
            names = f.list();
            for (String name : names) {
        		if(Tools.afterLast(name,".").equals("json")){
        			String val=Tools.beforeFirst(name,".");
        			if(val.matches("\\d+")) {
        				arrlist.add(Integer.parseInt(val));
        			}
        		}
            }
            int[] data = setUnique(toIntarray(arrlist.toArray()));
            Arrays.sort(data);
            if(data.length>0) {
        		result="[";
        		for (int value : data){
        			result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
        		}
        		result=result.substring(0, result.length()-1);
        		result+=']';
            }else {
            	result="[]";
            }
    	}

    	if(fn.equals("ndwi_list")) {
    		
    		List<Integer> arrlist = new ArrayList<Integer>();
    		
            File f = new File(NDWIPath);
            String[] names = f.list();
            for (String name : names) {
        		if(Tools.afterLast(name,".").equals("tiff")){
        			String val=Tools.beforeFirst(name,"_");
        			if(val.matches("\\d+")) {
        				arrlist.add(Integer.parseInt(val));
        			}else {
        				//Выбираю json с максимальным номером
        				int max=0;
        				File mf = new File(NDWIPath);
        				String[] mNames = mf.list();
        				for (String mName : mNames) {
        					String mVal=Tools.beforeFirst(mName,".");
        					if(mVal.matches("\\d+")) {
        						if(max<Integer.parseInt(mVal)) {
        							max=Integer.parseInt(mVal);	
        						}
        					}
        				}
        				arrlist.add(max);
        			}
        		}
            }
            int[] data = setUnique(toIntarray(arrlist.toArray()));
            Arrays.sort(data);
            if(data.length>0) {
        		result="[";
        		for (int value : data){
        			result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
        		}
        		result=result.substring(0, result.length()-1);
        		result+=']';
            }else {
            	result="[]";
            }
    	}

    	if(fn.equals("ndsi_list")) {
    		
    		List<Integer> arrlist = new ArrayList<Integer>();
    		
            File f = new File(NDSIPath);
            String[] names = f.list();
            for (String name : names) {
        		if(Tools.afterLast(name,".").equals("tiff")){
        			String val=Tools.beforeFirst(name,"_");
        			if(val.matches("\\d+")) {
        				arrlist.add(Integer.parseInt(val));
        			}else {
        				//Выбираю json с максимальным номером
        				int max=0;
        				File mf = new File(NDSIPath);
        				String[] mNames = mf.list();
        				for (String mName : mNames) {
        					String mVal=Tools.beforeFirst(mName,".");
        					if(mVal.matches("\\d+")) {
        						if(max<Integer.parseInt(mVal)) {
        							max=Integer.parseInt(mVal);	
        						}
        					}
        				}
        				arrlist.add(max);
        			}
        		}
            }
            int[] data = setUnique(toIntarray(arrlist.toArray()));
            Arrays.sort(data);
            if(data.length>0) {
        		result="[";
        		for (int value : data){
        			result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
        		}
        		result=result.substring(0, result.length()-1);
        		result+=']';
            }else {
            	result="[]";
            }
    	}

		if(fn.equals("smap_list")) {

			List<Integer> arrlist = new ArrayList<Integer>();

			File f = new File(SMAPPath);
			String[] names = f.list();
			for (String name : names) {
				if(Tools.afterLast(name,".").equals("tiff")){
					String val=Tools.beforeFirst(name,"_");
					if(val.matches("\\d+")) {
						arrlist.add(Integer.parseInt(val));
					}else {
						//Выбираю json с максимальным номером
						int max=0;
						File mf = new File(SMAPPath);
						String[] mNames = mf.list();
						for (String mName : mNames) {
							String mVal=Tools.beforeFirst(mName,".");
							if(mVal.matches("\\d+")) {
								if(max<Integer.parseInt(mVal)) {
									max=Integer.parseInt(mVal);
								}
							}
						}
						arrlist.add(max);
					}
				}
			}
			int[] data = setUnique(toIntarray(arrlist.toArray()));
			Arrays.sort(data);
			if(data.length>0) {
				result="[";
				for (int value : data){
					result += "{\"num\":\""+ String.valueOf(value)+"\", \"date\":\""+dayofyear2date(value)+"\"},";
				}
				result=result.substring(0, result.length()-1);
				result+=']';
			}else {
				result="[]";
			}
		}

    	return result;
    }
}
