package com.bonus.canteen.core.common.core.util;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.io.FileUtil;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class Base64DecodedMultipartFile implements MultipartFile {
   private final byte[] imgContent;
   private final String header;

   public Base64DecodedMultipartFile(byte[] imgContent, String header) {
      this.imgContent = imgContent;
      this.header = header.split(";")[0];
   }

   public static MultipartFile base64ToMultipart(String base64) {
      String[] baseSplit = base64.split(",");
      byte[] b = Base64.decode(baseSplit[1]);

      for(int i = 0; i < b.length; ++i) {
         if (b[i] < 0) {
            b[i] = (byte)(b[i] + 256);
         }
      }

      return new Base64DecodedMultipartFile(b, baseSplit[0]);
   }

   @Override
   public String getName() {
      double var10000 = (double)System.currentTimeMillis() + Math.random();
      return "" + var10000 + "." + this.header.split("/")[1];
   }

   @Override
   public String getOriginalFilename() {
      long var10000 = System.currentTimeMillis() + (long)((int)(Math.random() * 10000.0));
      return "" + var10000 + "." + this.header.split("/")[1];
   }

   @Override
   public String getContentType() {
      return this.header.split(":")[1];
   }

   @Override
   public boolean isEmpty() {
      return this.imgContent == null || this.imgContent.length == 0;
   }

   @Override
   public long getSize() {
      return (long)this.imgContent.length;
   }

   @Override
   public byte[] getBytes() throws IOException {
      return this.imgContent;
   }

   @Override
   public InputStream getInputStream() {
      return new ByteArrayInputStream(this.imgContent);
   }

   @Override
   public void transferTo(File dest) throws IOException, IllegalStateException {
      FileUtil.writeBytes(this.imgContent, dest);
   }
}
