package com.aip.gateway.api.service.impl;

import com.aip.gateway.api.aip.utils.AipFileStream;
import com.aip.gateway.api.aip.utils.AipFileUtils;
import com.aip.gateway.api.model.request.RequestStream;
import com.aip.gateway.api.model.request.RequestStreamAllSet;
import com.aip.gateway.api.model.request.RequestStreamDel;
import com.aip.gateway.api.model.request.RequestStreamSet;
import com.aip.gateway.api.model.response.ResponseInfo;
import com.aip.gateway.api.model.response.ResponseStream;
import com.aip.gateway.api.repository.AipFileRepository;
import com.aip.gateway.api.repository.AppRepository;
import com.aip.gateway.api.service.IApiStreamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Base64;

@Slf4j
@Service
public class ApiStreamService extends AbstractAipService implements IApiStreamService {

    public ApiStreamService(AppRepository repo, AipFileRepository aipFile) {
        super(repo, aipFile);
    }

    @Override
    public ResponseInfo getInfo(RequestStream req) {
        try {
            String tempOrgFileName = getRequestFileName(AipFileUtils.getFileNameWithoutExtension(req.getDispFileName()) + AipFileUtils.getExtension(req.getDispFileName()));
            String actualFileName = getActualFileName(req.getApiGuid() + AipFileUtils.getExtension(req.getDispFileName()));
            String newFileExt = getSupportedFileType(req.getDispFileName());
            if (newFileExt == null) {
                return new ResponseInfo(102, "지원하지 않는 파일형식 입니다.");
            }
            log.error("{}", tempOrgFileName);
            log.error("{}", actualFileName);

            byte[] fileDataArr = Base64.getDecoder().decode(req.getFileData());
            AipFileUtils.streamToFile(fileDataArr, tempOrgFileName);

            AipFileStream fileStream = new AipFileStream(req.getFileData());
            return responseGetFileInfo(this.aipFile.getManager().getFileInfo(fileStream, actualFileName), req.getDispFileName());
        }
        catch (Exception e) {
            return new ResponseInfo(109, "작업 중에 시스템 오류가 발생했습니다.");
        }
    }

    @Override
    public ResponseStream setLabel(RequestStreamSet req) {
        return null;
    }

    @Override
    public ResponseStream delLabel(RequestStreamDel req) {
        return null;
    }

    @Override
    public ResponseStream setProtection(RequestStreamSet req) {
        return null;
    }

    @Override
    public ResponseStream delProtection(RequestStreamDel req) {
        return null;
    }

    @Override
    public ResponseStream setLabelProtection(RequestStreamAllSet req) {
        return null;
    }

    @Override
    public ResponseStream delLabelProtection(RequestStreamDel req) {
        return null;
    }
}
