package com.mingliqiye.gitea.releases;

import com.mingliqiye.gitea.releases.entitys.Attachment;
import com.mingliqiye.gitea.releases.entitys.CreateReleaseOption;
import com.mingliqiye.gitea.releases.entitys.Release;
import com.mingliqiye.gitea.releases.entitys.StringKeyValue;
import com.mingliqiye.gitea.releases.http.HttpRelease;
import com.mingliqiye.libs.meta.ManifestReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.cli.*;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

@Slf4j
public class Main {
    public static CommandLine cmd;
    public static List<File> files = new ArrayList<>();

    public static void getFiles(File file) {

        if (file.isDirectory()) {
            log.info("search directory {}", file.getAbsolutePath());
            Arrays.stream(file.listFiles()).forEach(Main::getFiles);
        } else {
            if (file.exists()) {
                files.add(file);
            } else {
                log.warn("file not found {}", file.getAbsolutePath());
            }
            log.info("search file {} add.", file.getAbsolutePath());
        }
    }

    public static void main(String[] args) {
        init(args);
        Arrays.stream(cmd.getOptionValues("add-path")).forEach(s -> getFiles(new File(s)));
        String token = cmd.getOptionValue("token", () -> null);
        String serverUrl = cmd.getOptionValue("server-url", () -> null);
        String repositoryOwner = cmd.getOptionValue("repository-owner", () -> null);
        String repositoryName = cmd.getOptionValue("repository-name", () -> null);
        String title = cmd.getOptionValue("title", () -> null);
        String body = cmd.getOptionValue("body", () -> null);
        String tagName = cmd.getOptionValue("tag-name", () -> null);
        String targetCommitish = cmd.getOptionValue("target-commitish", () -> null);
        Boolean preRelease = Boolean.getBoolean(cmd.getOptionValue("pre-release", "false"));
        Boolean draft = Boolean.getBoolean(cmd.getOptionValue("draft", "false"));
        CreateReleaseOption createReleaseOption = new CreateReleaseOption();
        createReleaseOption.setName(title);
        createReleaseOption.setBody(body);
        createReleaseOption.setTag_name(tagName);
        createReleaseOption.setTarget_commitish(targetCommitish);
        createReleaseOption.setPrerelease(preRelease);
        createReleaseOption.setDraft(draft);
        StringKeyValue authorization = new StringKeyValue("Authorization", "token " + token);
        Release release = HttpRelease.createARelease(
                serverUrl, repositoryOwner, repositoryName, createReleaseOption, authorization);
        if (release == null) {
            log.error("release is null");
            exit(1);
            return;
        }
        log.info("release is {}", release);
        for (int i = 1; i <= files.size(); i++) {
            File file = files.get(i - 1);
            log.info("{}/{} -> uploading file {}", i, files.size(), file.getAbsolutePath());
            Attachment attachment = HttpRelease.createAReleaseAttachment(
                    serverUrl, repositoryOwner, repositoryName, release.getId(), file.getName(), file, authorization);
            if (attachment == null) {
                log.error("attachment is null : file {}", file.getAbsolutePath());
                exit(1);
                return;
            }
        }
    }

    public static void exit(Integer code) {
        if (code == null) {
            code = 1;
        }
        log.info("System exit by code: {}", code);
        System.exit(code);
    }

    public static void init(String[] args) {

        Options options = new Options();
        Option help = new Option("h", "help", false, "显示帮助信息");
        Option info = new Option("i", "info", false, "显示帮助信息");
        Option token = new Option("t", "token", true, "token 不 包含 前缀的token");
        Option repositoryOwner = new Option("o", "repository-owner", true, "团队名");
        Option repositoryName = new Option("r", "repository-name", true, "仓库名");
        Option title = new Option("ti", "title", true, "releases的标题");
        Option body = new Option("b", "body", true, "releases的描述");
        Option serverUrl = new Option("s", "server-url", true, "服务器url");
        Option tagName = new Option("tn", "tag-name", true, "标签名");
        Option targetCommitish = new Option("tc", "target-commitish", true, "提交版本");
        Option preRelease = new Option("p", "pre-release", true, "是否为预发布");
        Option draft = new Option("d", "draft", true, "是否为草稿");
        Option addPath = new Option("a", "add-path", true, "添加文件和目录 目录下的所有文件都会加入到 releases 包括递归子目录");
        options.addOption(help);
        options.addOption(info);
        options.addOption(token);
        options.addOption(repositoryOwner);
        options.addOption(repositoryName);
        options.addOption(title);
        options.addOption(body);
        options.addOption(serverUrl);
        options.addOption(tagName);
        options.addOption(targetCommitish);
        options.addOption(preRelease);
        options.addOption(draft);
        options.addOption(addPath);
        CommandLineParser parser = new DefaultParser();
        HelpFormatter formatter = new HelpFormatter();
        try {
            cmd = parser.parse(options, args);

            Arrays.stream(cmd.getOptions()).forEach(option ->
                    log.info("arg:{}={}",option.getKey(),option.getValue())
            );
            if (cmd.hasOption("h")) {
                formatter.printHelp(" ", options);
                exit(0);
            }
            if (cmd.hasOption("i")) {
                ManifestReader.getManifestData().properties().forEach(i -> {
                    System.out.println(i.getKey() + " : " + i.getValue());
                });

                exit(0);
            }
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
        }
    }
}