package com.upyuns.platform.rs.website.util;

import it.geosolutions.geoserver.rest.GeoServerRESTManager;
import it.geosolutions.geoserver.rest.GeoServerRESTPublisher;
import it.geosolutions.geoserver.rest.decoder.RESTCoverageStore;
import it.geosolutions.geoserver.rest.encoder.GSResourceEncoder;

import java.io.File;
import java.io.FileNotFoundException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;

public class GeoServerUtil {

    /**
     * geoServer配置
     */
    private static String url = "http://10.5.52.4:18080/geoserver";

    private static String geoUsername = "admin";

    private static String geoPassword = "upyuns";


    public static GeoServerRESTManager getManager() throws MalformedURLException {
        URL u = new URL(url);
        //获取管理对象
        GeoServerRESTManager geoServerRESTManager = new GeoServerRESTManager(u, geoUsername, geoPassword);
        return geoServerRESTManager;
    }

    /**
     * 判断工作区（workspace）是否存在，不存在则创建
     */
    public static boolean judgeWorkSpace(String workspace) throws MalformedURLException {
        boolean flag = false;
        GeoServerRESTManager manager = getManager();
        GeoServerRESTPublisher publisher = manager.getPublisher();
        List<String> workspaces = manager.getReader().getWorkspaceNames();
        if (!workspaces.contains(workspace)) {
            boolean createWorkspace = publisher.createWorkspace(workspace);
            flag = true;
            System.out.println("create workspace : " + createWorkspace);
        } else {
            flag = false;
            System.out.println("workspace已经存在了,workspace :" + workspace);
        }
        return flag;
    }

    /**
     * 当发布图层时会自动创建数据储存，于是我把创建数据储存的方法删除了
     *
     * @param store     存储名
     * @param workSpace 工作空间名
     * @param filePath  要发布的图层的硬盘的目录地址
     * @param layerName 要发布的图层的名字
     * @param style     发布图层使用的样式，因为我的几个样式已经提前传到工作空间了，所以就没有用代码
     * @return boolean
     */
    public static boolean shpJudgeDatabase(String workSpace, String store, String filePath, String layerName, String style) {
        GeoServerRESTManager manager = null;
        RESTCoverageStore restStore = null;

        try {

            manager = getManager();
            GeoServerRESTPublisher publisher = manager.getPublisher();
//                   
            boolean publish = publisher.publishGeoTIFF(workSpace, store, layerName, new File(filePath), "EPSG:4326",
                    GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED, style, null);
            System.out.println("publish (TIFF文件发布状态) : " + publish);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return false;
    }

    /**
     * 当发布图层时会自动创建数据储存，于是我把创建数据储存的方法删除了
     *
     * @param store     存储名
     * @param workSpace 工作空间名
     * @param filePath  要发布的图层的硬盘的目录地址
     * @param layerName 要发布的图层的名字
     * @param style     发布图层使用的样式，因为我的几个样式已经提前传到工作空间了，所以就没有用代码
     * @return boolean
     */
    public static boolean publishGeoTIFF(String workSpace, String store, String filePath, String layerName, String style) {
        GeoServerRESTManager manager = null;
//        RESTCoverageStore restStore = null;

        try {
//            URL  urlShapefilePath = new URL("file://"+ filePath);
            manager = getManager();
            GeoServerRESTPublisher publisher = manager.getPublisher();
//            boolean result = false;
//            GSGeoTIFFDatastoreEncoder storeEncoder = new GSGeoTIFFDatastoreEncoder(store, urlShapefilePath);
//            result = manager.getStoreManager().create(workSpace, storeEncoder);
//            if(result) {
                boolean publish = publisher.publishGeoTIFF(workSpace, store, layerName, new File(filePath), "EPSG:4326",
                        GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED, style, null);
                System.out.println("publish (TIFF文件发布状态) : " + publish);
//            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) throws MalformedURLException, FileNotFoundException, URISyntaxException {
        GeoServerRESTManager  manager = GeoServerUtil.getManager();
        Boolean flag = manager.getReader().existsDatastore("test", "mt-VC-202312-yangxi-a-2public");
        Boolean flag2 = manager.getReader().existsCoveragestore("test", "mt-VC-202312-yangxi-a-2public");
        Boolean flag3 = manager.getReader().existsDatastore("rsinsure2", "mt-rsinsure2farmblock-2024-231224206201-a-0public");
        GeoServerRESTPublisher publisher = manager.getPublisher();

//        try {
//            // 数据存储需要的文件
////            String shpFilePath = String.format("file://%s", "/sdbdata/geoserver/data_insure2/block/230781/mt-farmblock-2023-230781202-a-0public/mt-farmblock-2023-230781202-a-0public.shp");
//            String shpFilePath = String.format("file://%s", "/sdbdata/geoserver/data_insure2/block/230781/mt-farmblock-2023-230781202-a-0public/mt-farmblock-2023-230781202-a-0public.shp");
//            URL urlShapeFile = new URL(shpFilePath);
//            // 创建数据集
//            GSShapefileDatastoreEncoder datastoreEncoder = new GSShapefileDatastoreEncoder("mt-rsinsure3farmblock6", urlShapeFile);
//            datastoreEncoder.setCharset(Charset.forName("UTF-8"));
//            datastoreEncoder.setType("shapefile");
//            datastoreEncoder.setE
//            manager.getStoreManager().create("rsinsure3", datastoreEncoder);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }


        ///Users/zhoujianwei/Downloads/农险平安202410/mt-rsinsure3farmblock/mt-rsinsure3farmblock.shp
//        boolean publish = publisher.publishShp("rsinsure3", "mt-rsinsure3farmblock", (NameValuePair[])null, "mt-rsinsure3farmblock", GeoServerRESTPublisher.UploadMethod.EXTERNAL, new URI("file:///sdbdata/geoserver/data_insure3/mt-rsinsure3farmblock/mt-rsinsure3farmblock.shp"), "EPSG:4326",(String)null,
//                GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED, "polygon");
//        try {
//            // 数据存储需要的文件
//            String shpFilePath = String.format("file://%s", "/sdbdata/geoserver/data_insure3/mt-rsinsure3farmblock/mt-rsinsure3farmblock.shp");
//            URL urlShapeFile = new URL(shpFilePath);
//            // 创建数据集
//            GSShapefileDatastoreEncoder datastoreEncoder = new GSShapefileDatastoreEncoder("mt-rsinsure3farmblock2", urlShapeFile);
//            datastoreEncoder.setCharset(Charset.forName("UTF-8"));
//            manager.getStoreManager().create("rsinsure3", datastoreEncoder);
//        } catch (MalformedURLException e) {
//            e.printStackTrace();
//        }


//        if (!restReader.existsLayer(workSpace, layerName)) {
//            try {
//                GSFeatureTypeEncoder gsFeatureTypeEncoder = new GSFeatureTypeEncoder();
//                gsFeatureTypeEncoder.setTitle("mt-rsinsure3farmblock2");
//                gsFeatureTypeEncoder.setName("mt-rsinsure3farmblock2");
//                gsFeatureTypeEncoder.setSRS(GeoServerRESTPublisher.DEFAULT_CRS);
//
//                GSLayerEncoder gsLayerEncoder = new GSLayerEncoder();
//                gsLayerEncoder.addStyle("polygon");
//
//                boolean layer = publisher.publishDBLayer("rsinsure3", "mt-rsinsure3farmblock2", gsFeatureTypeEncoder, gsLayerEncoder);
//                System.out.println("publish layer : " + layer);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//        GSFeatureTypeEncoder featureTypeEncoder = new GSFeatureTypeEncoder();
//        featureTypeEncoder.setName("mt-rsinsure3farmblock2");
//        featureTypeEncoder.setTitle("mt-rsinsure3farmblock2");
//        featureTypeEncoder.setSRS(GeoServerRESTPublisher.DEFAULT_CRS);
//
//        featureTypeEncoder.setProjectionPolicy(GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED);
//        if (!publisher.createResource("rsinsure3", GeoServerRESTPublisher.StoreType.DATASTORES, "mt-rsinsure3farmblock2", featureTypeEncoder)) {
//
//        } else {
//            GSLayerEncoder layerEncoder = publisher.configureDefaultStyle("polygon");
//            publisher.configureLayer("rsinsure3", "mt-rsinsure3farmblock2", layerEncoder);
//        }
//    }

//        String layerName = "mt-rsinsure3farmblock2";
//        if (!manager.getReader().existsLayer("rsinsure3", layerName)) {
//            try {
//                GSFeatureTypeEncoder gsFeatureTypeEncoder = new GSFeatureTypeEncoder();
//                gsFeatureTypeEncoder.setTitle(layerName);
//                gsFeatureTypeEncoder.setName(layerName);
//                gsFeatureTypeEncoder.setSRS(GeoServerRESTPublisher.DEFAULT_CRS);
//
//                GSLayerEncoder gsLayerEncoder = new GSLayerEncoder();
//                gsLayerEncoder.addStyle("polygon");
//
////                boolean layer = publisher.configureLayer("rsinsure3", "mt-rsinsure3farmblock3", gsLayerEncoder);
//                boolean layer = publisher.publishDBLayer("rsinsure3", "mt-rsinsure3farmblock2", gsFeatureTypeEncoder, gsLayerEncoder);
//                System.out.println("publish layer : " + layer);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }


//        GSFeatureTypeEncoder featureTypeEncoder = new GSFeatureTypeEncoder();
//        featureTypeEncoder.setName("mt-rsinsure3farmblock2");
//        featureTypeEncoder.setTitle("mt-rsinsure3farmblock2");
//        featureTypeEncoder.setSRS(GeoServerRESTPublisher.DEFAULT_CRS);
//        featureTypeEncoder.setNativeCRS(GeoServerRESTPublisher.DEFAULT_CRS);
//
//        featureTypeEncoder.setProjectionPolicy(GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED);
//        if (!publisher.createResource("rsinsure3", GeoServerRESTPublisher.StoreType.DATASTORES, "mt-rsinsure3farmblock2", featureTypeEncoder)) {
//
//        } else {
//            GSLayerEncoder layerEncoder = publisher.configureDefaultStyle("polygon");
//            publisher.configureLayer("rsinsure3", "mt-rsinsure3farmblock2", layerEncoder);
//        }
        //publishShp(String workspace, String storename, String layername, File zipFile, String srs)
        //
//        boolean publish = publisher.publishShp("rsinsure3", "mt-rsinsure3farmblock", "mt-rsinsure3farmblock", new File("/Users/zhoujianwei/Downloads/农险平安202410/mt-rsinsure3farmblock.zip"), GeoServerRESTPublisher.DEFAULT_CRS);
//                .publishShp("rsinsure3", "mt-rsinsure3farmblock", (NameValuePair[])null, "mt-rsinsure3farmblock", GeoServerRESTPublisher.UploadMethod.FILE, new File("/sdbdata/geoserver/data_insure3/block/mt-rsinsure3farmblock.zip"), "EPSG:4326",(String)null,
//                GSResourceEncoder.ProjectionPolicy.FORCE_DECLARED, "polygon");
//
//        File file = new File("/Users/zhoujianwei/Downloads/农险平安202410/mt-rsinsure3farmblock.zip");
////File file = new File("/Users/zhoujianwei/Downloads/农险平安202410/mt-rsinsure3farmblock/mt-rsinsure3farmblock.shp");
//        flag = publisher.publishShp("rsinsure3", "mt-rsinsure3farmblock",
//                new NameValuePair[]{new NameValuePair("charset", "UTF-8")},
//                "mt-rsinsure3farmblock",
//                GeoServerRESTPublisher.UploadMethod.FILE,
//                file.toURI(),
//                GeoServerRESTPublisher.DEFAULT_CRS,
//                "polygon");

        System.out.println(flag);
    }
}