package com.ruoyi.service.impl;

import com.ruoyi.domain.TestScenario;
import com.ruoyi.domain.TestType;
import com.ruoyi.domain.TestUseCase;
import com.ruoyi.domain.vo.MatrixColumnVO;
import com.ruoyi.domain.vo.MatrixRowVO;
import com.ruoyi.service.ITestScenarioService;
import com.ruoyi.service.ITestTypeService;
import com.ruoyi.service.MatrixService;
import com.ruoyi.service.TestUseCaseService;
import com.ruoyi.web.response.MatrixResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.format.TextStyle;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional
@Service
public class MatrixServiceImpl implements MatrixService {

    @Autowired
    private TestUseCaseService testUseCaseService;

    @Autowired
    private ITestScenarioService testScenarioService;

    @Autowired
    private ITestTypeService testTypeService;

    @Override
    public MatrixResponse getMatrix() {

        List<TestUseCase> useCases = testUseCaseService.list();
        List<TestScenario> scenarios = testScenarioService.list();
        List<TestType> types = testTypeService.list();

        MatrixResponse response = new MatrixResponse();
        setHeader(response, types);
        setRows(response, scenarios, types, useCases);

        return response;
    }

    private void setHeader(MatrixResponse response, List<TestType> types) {

        List<MatrixColumnVO> columns = new ArrayList();

        for(TestType type : types) {
            MatrixColumnVO column = new MatrixColumnVO(String.valueOf(type.getId()), type.getTestType());
            columns.add(column);
        }

        response.setHeader(columns);

    }

    private void setRows(MatrixResponse response, List<TestScenario> scenarios, List<TestType> types, List<TestUseCase> useCases) {

        List<Map<String, Object>> rows = new ArrayList();


        for(TestScenario scenario : scenarios) {

            Map<String, Object> row = new HashMap();
            row.put("name", scenario.getTestScenario());

            for(TestType type : types) {
                String columnId = String.valueOf(type.getId());
                String coordinates = scenario.getId() + columnId;
                Long useCaseId = getUseCaseIdByCoordinates(useCases, coordinates);
                row.put(columnId, useCaseId == null ? "" : String.valueOf(useCaseId));
            }

            rows.add(row);
        }

        response.setRows(rows);
    }

    public Long getUseCaseIdByCoordinates(List<TestUseCase> useCases, String coordinates) {

        for(TestUseCase useCase : useCases) {
            if(useCase.getCoordinates().equals(coordinates)) {
                return useCase.getId();
            }
        }
        return null;
    }
}