package com.lanyuanxiaoyao.service.executor.task.functions.police;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.lanyuanxiaoyao.service.executor.core.TaskContext;
import com.lanyuanxiaoyao.service.executor.task.entity.Prisoner;
import org.apache.flink.streaming.api.functions.sink.RichSinkFunction;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

/**
 * @author lanyuanxiaoyao
 */
public class PrisonerSink extends RichSinkFunction<Prisoner> {
    private final TaskContext taskContext;
    private FileSystem fileSystem;

    public PrisonerSink(TaskContext taskContext) {
        this.taskContext = taskContext;
    }

    @Override
    public void open(org.apache.flink.configuration.Configuration parameters) throws Exception {
        super.open(parameters);
        this.fileSystem = FileSystem.get(new Configuration());
    }

    @Override
    public void close() throws Exception {
        super.close();
        if (ObjectUtil.isNotNull(fileSystem)) {
            fileSystem.close();
        }
    }

    @Override
    public void invoke(Prisoner value, Context context) throws Exception {
        Path p = new Path(StrUtil.format("{}/{}/{}/{}/records", taskContext.getResultPath(), taskContext.getTaskId(), value.getPartition(), value.getKey()));
        if (fileSystem.exists(p)) {
            try (FSDataOutputStream outputStream = fileSystem.append(p)) {
                outputStream.writeBytes(value.toString());
            }
        } else {
            try (FSDataOutputStream outputStream = fileSystem.create(p, true)) {
                outputStream.writeBytes(value.toString());
            }
        }
    }
}
