package com.cyksj.common.util;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

/**
 * @author valor.
 * @date 2019/8/25 15:10
 */
public class IoKit {

    private static final int buf_size = 8192;

    private IoKit() {}

    public enum Charsets {
        UTF_8("utf-8", StandardCharsets.UTF_8);

        private String value;

        private Charset charset;

        Charsets(String value, Charset charset) {
            this.value = value;
            this.charset = charset;
        }

        public String getValue() {
            return this.value;
        }

        public Charset getCharset() {
            return charset;
        }
    }

    /**
     * default charset 'UTF-8'
     */
    public static String toString(byte[] bytes) {
        return toString(bytes, Charsets.UTF_8);
    }

    public static String toString(byte[] bytes, Charsets charset) {
        return new String(bytes, charset.getCharset());
    }

    /**
     * default charset 'UTF-8'
     */
    public static String toString(InputStream in) throws IOException {
        return toString(in, Charsets.UTF_8);
    }

    public static String toString(InputStream in, Charsets charset) throws IOException {
        return new String(toBytes(in), charset.getCharset());
    }

    public static byte[] toBytes(String str) {
        return toBytes(str, Charsets.UTF_8);
    }

    public static byte[] toBytes(String str, Charsets charset) {
        return str.getBytes(charset.getCharset());
    }

    public static byte[] toBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        write(in, out);
        byte[] bytes = out.toByteArray();
        close(out);
        return bytes;
    }

    /**
     * default charset 'UTF-8'
     */
    public static void write(String var, OutputStream out) throws IOException {
        write(var, out, Charsets.UTF_8);
    }

    public static void write(String var, OutputStream out, Charsets charset) throws IOException {
        out.write(var.getBytes(charset.getCharset()));
    }

    public static void write(byte[] var, OutputStream out) throws IOException {
        out.write(var);
    }

    public static void write(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[buf_size];

        int readSize;
        while (true) {
            readSize = in.read(buffer);
            if (readSize < 0) {
                break;
            }
            out.write(buffer, 0, readSize);
        }
        out.flush();

        // close
        close(in);
    }

    public static void close(Closeable closeable) {
        if (null != closeable) {
            try {
                closeable.close();
            } catch (IOException e) {
                // ignore exception
                e.printStackTrace();
            }
        }
    }
}
