package com.jsc.dsp.service;

import com.jsc.dsp.binding.FileDlBinding;
import com.jsc.dsp.utils.FileUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Base64.Decoder;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@EnableBinding(FileDlBinding.class)
public class FileDlService extends StreamService {

    @Autowired
    FileDlBinding source;

    @Autowired
    Decoder base64;

    @Autowired
    JacksonJsonParser jsonParser;

    @Value("${custom.proto_save_path}")
    String protoSavePath;

    @Value("${custom.transfer_backup_path}")
    String transferBackupPath;

    @Value("${custom.file_unzip_path}")
    String fileUnzipPath;

    @Value("${custom.nginx_path}")
    String nginxPath;

    @Value("${custom.keep_backup_file}")
    String keepBackupFile;

    private final Logger logger = LogManager.getLogger(FileDlService.class.getName());
    private final FileUtils fileUtils = new FileUtils();
    private final ExecutorService pool = Executors.newFixedThreadPool(25);


    @Override
    public void sendMessage(byte[] msg) {
        source.fileDlOutPut().send(MessageBuilder.withPayload(msg).build());
    }

    @Override
    @StreamListener(FileDlBinding.FILE_DL_PIPELINE_IN)
    public void receiveMessage(Object payload) {
        try {
            String tempString = new String(base64.decode(payload.toString()), StandardCharsets.UTF_8);
            Map<String, Object> data = jsonParser.parseMap(tempString);
            String fileName = data.get("fileName").toString();
            String fileURL = data.get("url").toString();
            StringBuilder fullPath = new StringBuilder();
            fullPath.append(protoSavePath).append(fileName);
            //判断路径是否存在，不存在则创建
            int lastIndex = fullPath.lastIndexOf("/");
            if (lastIndex <= 0) {
                lastIndex = fullPath.lastIndexOf("\\");
            }
            File file = new File(fullPath.substring(0, lastIndex));
            if (!file.exists()) {
                file.mkdirs();
            }
            int dlResult = fileUtils.downloadFromUrl(fileURL, protoSavePath);
            if (dlResult == 1) {
                File transferPath = new File(transferBackupPath);
                File[] files = transferPath.listFiles();
                if (files != null && files.length > 0) {
                    for (File transferFile : files) {
                        if (transferFile.getName().endsWith(".tar.gz")) {
                            if (transferFile.getName().startsWith("attach")) {
                                try {
                                    fileUtils.UnzipTarGzip(transferFile.getAbsolutePath(), nginxPath);
                                    logger.info("Unzip attachments " + transferFile.getName());
                                } catch (Exception e) {
                                    logger.error("Unzip error!");
                                }
                            } else {
                                try {
                                    fileUtils.UnzipTarGzip(transferFile.getAbsolutePath(), fileUnzipPath);
                                    logger.info("Unzip " + transferFile.getName());
                                } catch (Exception e) {
                                    logger.error("Unzip error!");
                                }
                            }
                        }
                        fileUtils.moveFileToBackupFolder(transferFile, keepBackupFile);
                    }
//                    Runnable upload2Ceph = () -> fileUtils.uploadToCeph(fileUnzipPath);
//                    pool.execute(upload2Ceph);
                }
            } else if (dlResult == 0) {
                logger.error("File " + fileName + " download failure");
            }
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

}
