package cn.sagacloud.server.algorithm.services.http

import java.awt.image.BufferedImage
import java.io.*
import java.net.HttpURLConnection
import java.net.MalformedURLException
import java.net.URL
import javax.imageio.ImageIO

/**
 *
 *
 * @author jxing
 */
object HttpService {


    /**
     * 向指定URL发送GET方法的请求
     *
     * @param urlNameString
     * 发送请求的URL
     * @return InputStream 所代表远程资源的响应结果
     */
    fun getInputStream(urlNameString: String?): InputStream? {
        var urlNameString = urlNameString
        val inBR: BufferedReader? = null
        try { // 兼容camel的http4
            if (urlNameString != null && urlNameString.startsWith("http4")) urlNameString = urlNameString.replaceFirst("http4".toRegex(), "http")
            //String urlNameString = url + "?" + param;
            val realUrl = URL(urlNameString)
            // 打开和URL之间的连接
            val connection = realUrl.openConnection()
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*")
            connection.setRequestProperty("connection", "Keep-Alive")
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            // 建立实际的连接
            connection.connect()
            return connection.getInputStream()
        } catch (e: Exception) {
            println("获取图片异常！$e")
            e.printStackTrace()
        } // 使用finally块来关闭输入流
        finally {
            try {
                inBR?.close()
            } catch (e2: Exception) {
                e2.printStackTrace()
            }
        }
        return null
    }



    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param _url
     * 发送请求的 URL
     * @param image
     * 图片的BufferedImage
     * @return 所代表远程资源的响应结果
     */
    fun sendImageFile(_url: String?, image: BufferedImage): String {
        var url = _url
        val out: PrintWriter? = null
        var inputBR: BufferedReader? = null
        var result = ""
        try {
            // 兼容camel的http4
            if (url != null && url.startsWith("http4"))
                url = url.replaceFirst("http4".toRegex(), "http")
            val realUrl = URL(url!!)
            // 打开和URL之间的连接
            val conn = realUrl.openConnection()
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*")
            conn.setRequestProperty("Content-Type", "image/jpg")
            conn.setRequestProperty("connection", "Keep-Alive")
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            // 发送POST请求必须设置如下两行
            conn.doOutput = true
            conn.doInput = true
            val outputStream = conn.getOutputStream()
            ImageIO.write(image, "JPG", outputStream)
            outputStream.flush()
            inputBR = BufferedReader(
                    InputStreamReader(conn.getInputStream()))
            var line: String?
            line = inputBR.readLine()
            while (line != null) {
                result += line
                line = inputBR.readLine()
            }
        } catch (e: Exception) {
            println("发送 POST 请求出现异常！$e")
            e.printStackTrace()
        } finally {
            try {
                out?.close()
                inputBR?.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
            }

        }//使用finally块来关闭输出流、输入流
        return result
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param _url
     * 发送请求的 URL
     * @param file
     * 图片的BufferedImage
     * @return 所代表远程资源的响应结果
     */
    fun sendFile(_url: String?, file: InputStream): String {
        var url = _url
        val out: PrintWriter? = null
        var inputBR: BufferedReader? = null
        var result = ""
        try {
            // 兼容camel的http4
            if (url != null && url.startsWith("http4"))
                url = url.replaceFirst("http4".toRegex(), "http")
            val realUrl = URL(url!!)
            // 打开和URL之间的连接
            val conn = realUrl.openConnection()
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*")
            conn.setRequestProperty("Content-Type", "image/jpg")
            conn.setRequestProperty("connection", "Keep-Alive")
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            // 发送POST请求必须设置如下两行
            conn.doOutput = true
            conn.doInput = true
            val outputStream = conn.getOutputStream()
            outputStream.write(file.readBytes())
            outputStream.flush()
            inputBR = BufferedReader(
                    InputStreamReader(conn.getInputStream()))
            var line: String?
            line = inputBR.readLine()
            while (line != null) {
                result += line
                line = inputBR.readLine()
            }
        } catch (e: Exception) {
            println("发送 POST 请求出现异常！$e")
            e.printStackTrace()
        } finally {
            try {
                out?.close()
                inputBR?.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
            }

        }//使用finally块来关闭输出流、输入流
        return result
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param _url
     * 发送请求的 URL
     * @param file
     * 文件的ByteArray
     * @return 所代表远程资源的响应结果
     */
    fun sendFileByte(_url: String?, file: ByteArray): String {
        println("url : $_url")
        var url = _url
        val out: PrintWriter? = null
        var inputBR: BufferedReader? = null
        var result = ""
        try {
            // 兼容camel的http4
            if (url != null && url.startsWith("http4"))
                url = url.replaceFirst("http4".toRegex(), "http")
            val realUrl = URL(url!!)
            // 打开和URL之间的连接
            val conn = realUrl.openConnection()
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*")
            conn.setRequestProperty("Content-Type", "image/jpg")
            conn.setRequestProperty("connection", "Keep-Alive")
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            // 发送POST请求必须设置如下两行
            conn.doOutput = true
            conn.doInput = true
            val outputStream = conn.getOutputStream()
            outputStream.write(file)
            outputStream.flush()
            inputBR = BufferedReader(
                    InputStreamReader(conn.getInputStream()))
            var line: String?
            line = inputBR.readLine()
            while (line != null) {
                result += line
                line = inputBR.readLine()
            }
        } catch (e: Exception) {
            println("发送 POST 请求出现异常！$e")
            e.printStackTrace()
        } finally {
            try {
                out?.close()
                inputBR?.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
            }

        }//使用finally块来关闭输出流、输入流
        return result
    }


    /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     * 发送请求的 URL
     * @param param
     * 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    fun sendPost(url: String, param: Any): String {
        var out: PrintWriter? = null
        var inputBR: BufferedReader? = null
        var result = ""
        try {
            val realUrl = URL(url)
            // 打开和URL之间的连接
            val conn = realUrl.openConnection()
            // 设置连接超时
            conn.readTimeout = 5000
            conn.connectTimeout = 5000
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*")
            conn.setRequestProperty("connection", "Keep-Alive")
            conn.setRequestProperty("Content-Type", "application/json")
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            // 发送POST请求必须设置如下两行
            conn.doOutput = true
            conn.doInput = true
            // 获取URLConnection对象对应的输出流
            out = PrintWriter(conn.getOutputStream())
            // 发送请求参数
            out.print(param)
            // flush输出流的缓冲
            out.flush()
            // 定义BufferedReader输入流来读取URL的响应
            inputBR = BufferedReader(
                    InputStreamReader(conn.getInputStream()))
            var line: String?
            line = inputBR.readLine()
            while (line != null) {
                result += line
                line = inputBR.readLine()
            }
        } catch (e: Exception) {
            println("发送 POST 请求出现异常！$e")
            e.printStackTrace()
        } finally {
            try {
                out?.close()
                inputBR?.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
            }

        }//使用finally块来关闭输出流、输入流
        return result
    }

    /**
     * 向指定 URL 发送POST方法的请求
     * 带数据中心要求的header
     *
     * @param url
     * 发送请求的 URL
     * @param param
     * 请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    fun sendPostDataCenter(url: String, param: Any, projectId : String): String {
        var out: PrintWriter? = null
        var inputBR: BufferedReader? = null
        var result = ""
        try {
            val realUrl = URL(url)
            // 打开和URL之间的连接
            val conn = realUrl.openConnection()
            // 设置连接超时
            conn.readTimeout = 80000
            conn.connectTimeout = 80000
            // 设置通用的请求属性
            conn.setRequestProperty("accept", "*/*")
            conn.setRequestProperty("connection", "Keep-Alive")
            conn.setRequestProperty("Content-Type", "application/json")
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)")
            conn.setRequestProperty("Coming", "RevitAlgorithm")
            conn.setRequestProperty("ProjectId", projectId)
            // 发送POST请求必须设置如下两行
            conn.doOutput = true
            conn.doInput = true
            // 获取URLConnection对象对应的输出流
            out = PrintWriter(conn.getOutputStream())
            // 发送请求参数
            out.print(param)
            // flush输出流的缓冲
            out.flush()
            // 定义BufferedReader输入流来读取URL的响应
            inputBR = BufferedReader(
                    InputStreamReader(conn.getInputStream()))
            var line: String?
            line = inputBR.readLine()
            while (line != null) {
                result += line
                line = inputBR.readLine()
            }
        } catch (e: Exception) {
            println("发送 POST 请求出现异常！$e")
            e.printStackTrace()
        } finally {
            try {
                out?.close()
                inputBR?.close()
            } catch (ex: IOException) {
                ex.printStackTrace()
            }

        }//使用finally块来关闭输出流、输入流
        return result
    }


    /**
     * 获取网络文件大小
     * @param url1
     * @return
     * @throws IOException
     */
    @Throws(IOException::class)
    fun getFileLength(url1: String): Long {
        var length = 0L
        val url: URL
        try {
            url = URL(url1)
            val urlcon = url.openConnection() as HttpURLConnection
            //根据响应获取文件大小
            length = urlcon.contentLengthLong
            urlcon.disconnect()
        } catch (e: MalformedURLException) {
            e.printStackTrace()
        } catch (e: IOException) {
            e.printStackTrace()
        }
        return length
    }
}