package link.at17.mid.tushare.system.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.AccessLevel;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

@Data
@Accessors(chain=true)
public class CsvOutput {
    
    @Setter(AccessLevel.PRIVATE)
    private boolean headerSet = false;
    @Setter(AccessLevel.PRIVATE)
    @Getter(AccessLevel.PRIVATE)
    private int headerSize = 0;
    @Setter(AccessLevel.PRIVATE)
    @Getter(AccessLevel.PRIVATE)
    private int currColIndex = 0;
    private List<String> headers = new ArrayList<>();
    private List<String[]> lines = new ArrayList<>();
    
    public CsvOutput() {
        
    }
    
    public CsvOutput setHeaders(String...headers) {
        if (headerSet) {
            return this;
        }
        this.headers.clear();
        this.headers.addAll(Arrays.asList(headers));
        headerSize = this.headers.size();
        headerSet = true;
        return this;
    }
    
    public CsvOutput setHeadersSplit(String headers) {
        return setHeadersSplit(headers, ",");
        
    }
    
    public CsvOutput setHeadersSplit(String headers, String splitBy) {
        return setHeaders(headers.split(splitBy));
    }
    
    public CsvOutput addLine(Object...values) {
        String[] line = new String[headerSize];
        for (int i = 0; i < headerSize; i++) {
            line[i] = values[i].toString();
        }
        lines.add(line);
        return this;
    }
    
    public CsvOutput saveTo(String path) {
        File file = new File(path);
        try {
            OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(file));
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(new String(new byte[]{(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}));
            bw.write(String.join(",", headers));
            bw.write("\r\n");
            for (String[] line : lines) {
                bw.write(String.join(",", line));
                    bw.write("\r\n");
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return this;
    }

}
