package com.mingliqiye.gitea.releases.http;

import com.alibaba.fastjson2.JSON;
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.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.File;
import java.io.IOException;

@Slf4j
public class HttpRelease {
    public static OkHttpClient client = new OkHttpClient();

    /**
     * 创建releasesApi<p>
     * create release api<p>
     * {baseurl}/{owner}/{repo}<p>
     * https://git.mingliqiye.com/Actions/com.mingliqiye.gitea.releases/<p>
     * 注意: 创建release 不包含附件<p>
     * Note: Creating a release does not include attachments.<p>
     * api 地址 https://docs.gitea.com/zh-cn/api/#tag/repository/operation/repoCreateRelease<p>
     * api url https://docs.gitea.com/api/#tag/repository/operation/repoCreateRelease
     * @param baseurl http://your.gitea.url 你的gitea地址 your gitea url
     * @param owner 所属组织 organization
     * @param repo 仓库名 repertoty
     * @param createReleaseOption 创建发布选项 create release option
     * @see Release
     * @see CreateReleaseOption
     * @return
     *
     */
    public static Release createARelease(
            String baseurl,
            String owner,
            String repo,
            CreateReleaseOption createReleaseOption,
            StringKeyValue authorization) {
        String url = StringUtils.format("{}/api/v1/repos/{}/{}/releases", baseurl, owner, repo);
        MediaType json = MediaType.parse("application/json; charset=utf-8");
        log.info("{}", createReleaseOption);
        String jsondata = JSON.toJSONString(createReleaseOption);
        RequestBody body = RequestBody.create(jsondata, json);
        Request request = new Request.Builder()
                .url(url)
                .addHeader(authorization.getKey(), authorization.getValue())
                .post(body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                log.info("CreateReleaseOK");
                return JSON.parseObject(response.body().string(), Release.class);
            } else {
                log.error("CreateReleaseFailed");
                log.error("Response.body:{}", response.body().string());
            }
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return null;
    }

    public static Attachment createAReleaseAttachment(
            String baseurl,
            String owner,
            String repo,
            Long id,
            String name,
            File attachment,
            StringKeyValue authorization) {
        String url = StringUtils.format("{}/api/v1/repos/{}/{}/releases/{}/assets", baseurl, owner, repo, id);

        if (attachment == null) {
            log.error("{}:{}", "attachment", "is a NullPointer");
            return null;
        }
        log.info("ReleaseAttachment start {}", attachment.getAbsolutePath());
        if (!attachment.exists()) {
            log.error("{}:{}", attachment.getAbsolutePath(), "is not exist");
            return null;
        } else if (!attachment.isFile()) {
            log.error("{}:{}", attachment.getAbsolutePath(), "is not a file");
            return null;
        } else if (!attachment.canRead()) {
            log.error("{}:{}", attachment.getAbsolutePath(), "permission denied can't read");
            return null;
        }
        RequestBody formBody = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart("name", name)
                .addFormDataPart(
                        "attachment",
                        attachment.getName(),
                        RequestBody.create(attachment, MediaType.parse("multipart/form-data")))
                .build();
        Request request = new Request.Builder()
                .url(url)
                .addHeader(authorization.getKey(), authorization.getValue())
                .post(formBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                log.info("ReleaseAttachment {} OK", attachment.getAbsolutePath());
                return JSON.parseObject(response.body().string(), Attachment.class);
            } else {
                log.error("ReleaseAttachment {} Failed", attachment.getAbsolutePath());
                log.error("Response.body:{}", response.body().string());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            e.printStackTrace();
        }
        return null;
    }
}
