package com.mooctest.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mooctest.data.BugHistoryDTO;
import com.mooctest.service.BugHistoryService;
import com.mooctest.util.HttpUtil;
import com.mooctest.util.MongoAPIUtil;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

import static com.mooctest.util.MongoAPIUtil.EMBEDDED_KEY;

@Service
public class BugHistoryServiceImpl implements BugHistoryService {

    public List<BugHistoryDTO> getBugHistory(List<String> bugIds) {

        HttpHeaders headers = MongoAPIUtil.createAuthHeaderForMongo();
        HttpEntity<String> entity = new HttpEntity<>(headers);

        String filterStr = MongoAPIUtil.genIdFilterStr(bugIds);

        String url = MongoAPIUtil.genFilterUrlWithMaxPage(MongoAPIUtil.CO_REPORT_DB, MongoAPIUtil.BUG_HISTORY_COLLECTION);

        RestTemplate rt = HttpUtil.getRestTemplate();
        ResponseEntity<JSONObject> dto = rt.exchange(url, HttpMethod.GET, entity, JSONObject.class, filterStr);

        return extractData(dto.getBody().getJSONArray(EMBEDDED_KEY));
    }


    public List<BugHistoryDTO> extractData(JSONArray jsonArray) {
        if (jsonArray.size() == 0) {
            return null;
        }
        return jsonArray.toJavaList(BugHistoryDTO.class);
    }
}
