package com.bonus.core.menuai.utils;

import lombok.SneakyThrows;
import org.apache.http.entity.ContentType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URL;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class MenuaiUtils {
   private static final Logger log = LoggerFactory.getLogger(MenuaiUtils.class);

   public static File getFile(String url) {
      String fileName = url.substring(url.lastIndexOf("."));
      File file = null;
      InputStream inStream = null;
      OutputStream os = null;

      try {
         file = File.createTempFile("net_url", fileName);
         URL urlfile = new URL(url);
         inStream = urlfile.openStream();
         os = new FileOutputStream(file);
         byte[] buffer = new byte[8192];

         int bytesRead;
         while((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
            os.write(buffer, 0, bytesRead);
         }
      } catch (Exception var16) {
         log.error("文件下载失败", var16);
      } finally {
         try {
            if (null != os) {
               os.close();
            }

            if (null != inStream) {
               inStream.close();
            }
         } catch (Exception var15) {
            log.error("文件下载失败", var15);
         }

      }

      return file;
   }

   public static boolean isHostConnectable(String host, int port) {
      Socket socket = new Socket();

      boolean var4;
      try {
         socket.connect(new InetSocketAddress(host, port));
         return true;
      } catch (IOException var14) {
         var4 = false;
      } finally {
         try {
            socket.close();
         } catch (IOException var13) {
            log.error("关闭socket失败", var13);
         }

      }

      return var4;
   }

   @SneakyThrows
   public static MultipartFile fileToMultipartFile(File file) {
      try {
         FileInputStream fileInputStream = new FileInputStream(file);
         return new MockMultipartFile(file.getName(), file.getName(), ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
      } catch (Throwable var2) {
         throw var2;
      }
   }

   public static String LocalDateToStrByPattern(String pattern, LocalDate localDate) {
      DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
      return df.format(localDate);
   }
}
