package com.bcxin.backend.domain.snapshoots;

import com.alibaba.fastjson.JSONObject;
import com.bcxin.backend.core.utils.SecurityUtil;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import org.springframework.util.StringUtils;

import java.io.File;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Data
public class RequestSnapshoot {
    private String method;
    private String path;
    private String query;
    private String proxy;
    private JSONObject headers;
    private String body;
    @JsonProperty("X-url")
    private String xUrl;

    private Collection<FileItem> fileItems;

    public void addFileItem(String srcFileUrl) {
        if (!StringUtils.hasLength(srcFileUrl)) {
            return;
        }

        if (this.getFileItems() == null) {
            this.setFileItems(new ArrayList<>());
        }

        FileItem fileItem = new FileItem();
        fileItem.setSrcFileUrl(srcFileUrl);

        DateFormat dt = new SimpleDateFormat("yyyyMM");
        String targetUrl = String.format("/uploads/sync/%s/%s-%s", dt.format(new Date()),
                UUID.randomUUID().toString(), Paths.get(srcFileUrl).toFile().getName());
        fileItem.setTargetFileUrl(targetUrl);
        this.getFileItems().add(fileItem);
    }

    public String getUserId() {
        JSONObject request = headers.getJSONObject("request");
        String token = null;
        if (request != null) {
            token = request.getString("accesstoken");
            if (!StringUtils.hasLength(token)) {
                if (StringUtils.hasLength(query) && query.contains("accessToken")) {
                    Optional<String> accessTokenOptional =
                            Arrays.stream(query.split("&")).filter(ii -> ii.contains("accessToken"))
                                    .map(ii -> ii.substring(ii.indexOf("=") + 1))
                                    .findFirst();
                    if (accessTokenOptional.isPresent()) {
                        token = accessTokenOptional.get();
                    }
                }
            }
        }
        if (!StringUtils.hasLength(token)) {
            return null;
        }

        return SecurityUtil.getUserIdFromTokenWithoutVerify(token);
    }

    public boolean getHasFiles() {
        return this.getFileItems() != null && this.getFileItems().size() > 0;
    }

    @Data
    public static class FileItem {
        private String srcFileUrl;
        private String targetFileUrl;


    }
}
