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

import com.aip.gateway.api.aip.model.AipFileInfo;
import com.aip.gateway.api.aip.model.SetFileInfo;
import com.aip.gateway.api.aip.utils.AipFileUtils;
import com.aip.gateway.api.model.app.CheckAip;
import com.aip.gateway.api.model.response.ResponseBase;
import com.aip.gateway.api.model.response.ResponseFile;
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.utils.TimeUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.Date;

@Slf4j
@RequiredArgsConstructor
abstract class AbstractAipService {

    protected final AppRepository repo;
    protected final AipFileRepository aipFile;

    protected String getRequestFileName(String realFileName) {
        return this.repo.getSettings().getSourceFileDir() + realFileName;
    }
    protected String getActualFileName(String fileName) {
        return this.repo.getSettings().getTargetFileDir() + fileName;
    }

    protected String getSupportedFileType(String reqFileName) {
        return this.repo.getSupportedFileType(reqFileName);
    }

    protected CheckAip checkAipRequest(String apiGuid, String dispFileName, String realFileName, boolean isStream) {
        String reqFileName = "";
        if (isStream) {
            reqFileName = getRequestFileName(apiGuid + AipFileUtils.getExtension(dispFileName));
        }
        else {
            reqFileName = getRequestFileName(realFileName);
            if (!AipFileUtils.isExists(reqFileName)) {
                return new CheckAip(101, "파일이 존재하지 않습니다.", dispFileName);
            }
        }
        String newFileExt = getSupportedFileType(reqFileName);
        if (newFileExt == null) {
            return new CheckAip(102, "지원하지 않는 파일형식 입니다.", dispFileName);
        }

        CheckAip result = new CheckAip(0, "Success", dispFileName);
        result.setReqFileName(reqFileName);
        result.setNewFileExt(newFileExt);
        if (isStream) {
            result.setDispFileName(AipFileUtils.getFileNameWithoutExtension(dispFileName) + newFileExt);
        }
        else {
            result.setDispFileName(AipFileUtils.getFileNameWithoutExtension(realFileName) + newFileExt);
        }
        result.setActualFileName(getActualFileName(apiGuid + newFileExt));
        return result;
    }

    protected ResponseFile responseFileException(Exception exception, String displayFileName) {
        log.error("responseFileException: {}", exception.getMessage());
        return new ResponseFile(109, "작업 중에 시스템 오류가 발생했습니다.", displayFileName);
    }
    protected ResponseStream responseStreamException(Exception exception, String displayFileName) {
        log.error("responseFileException: {}", exception.getMessage());
        return new ResponseStream(109, "작업 중에 시스템 오류가 발생했습니다.", displayFileName);
    }

    private ResponseBase responseBase(SetFileInfo fileInfo, String displayFileName, String actualFileName) {
        ResponseBase result = new ResponseBase(fileInfo.errorNo, fileInfo.errorMsg, displayFileName);
        result.setFileExt(AipFileUtils.getExtension(displayFileName));
        result.setFileOwner(fileInfo.fileOwner);
        result.setFileSize(fileInfo.fileSize);
        result.setFileLabelGuid(fileInfo.labelGuid);
        result.setFileProtectionGuid(fileInfo.templateGuid);
        result.setNewFileName(displayFileName);
        result.setNewFileOwner(fileInfo.newFileOwner);
        result.setNewFileExt(AipFileUtils.getExtension(actualFileName));
        result.setNewFileSize(fileInfo.newFileSize);
        result.setNewFileLabelGuid(fileInfo.newFileLabelGuid);
        result.setNewFileProtectionGuid(fileInfo.newFileTemplateGuid);
        return result;
    }
    protected ResponseFile responseSetFile(SetFileInfo fileInfo, String displayFileName, String actualFileName) {
        ResponseBase baseResponse = responseBase(fileInfo, displayFileName, actualFileName);
        ResponseFile result = new ResponseFile(baseResponse);
        result.setOutputFileName(AipFileUtils.getFileName(actualFileName));
        return result;
    }
    protected ResponseStream responseSetStream(SetFileInfo fileInfo, String displayFileName, String actualFileName) {
        ResponseBase baseResponse = responseBase(fileInfo, displayFileName, actualFileName);
        ResponseStream result = new ResponseStream(baseResponse);
        result.setOutputFileName(AipFileUtils.getFileName(actualFileName));
        result.setFileData(AipFileUtils.getFileDataString(actualFileName));
        return result;
    }

    protected ResponseStream responseStreamFail(String displayFileName) {
        log.error("responseStreamFail: {}", displayFileName);
        return new ResponseStream(110, "작업 중에 파일 시스템 오류가 발생했습니다.", displayFileName);
    }
    protected ResponseInfo responseInfoException(Exception exception) {
        log.error("responseInfoException: {}", exception.getMessage());
        return new ResponseInfo(109, "작업 중에 시스템 오류가 발생했습니다.");
    }

    protected ResponseInfo responseGetFileInfo(AipFileInfo fileInfo, String displayFileName) {
        log.error("{}", fileInfo);
        boolean isLabled = false;
        boolean isProtected = false;
        Date creationTime = TimeUtils.getCurrentDate();
        String contentId  = "";
        String owner = "";
        String labelId  = "";
        String labelName  = "";
        String templateId  = "";
        String templateName  = "";
        long fileSize = 0;
        if (fileInfo != null) {
            fileSize = fileInfo.getFileSize();
            if (fileInfo.getContent() != null) {
                creationTime = fileInfo.getContent().getCreationTime();
            }
            if (fileInfo.getLabel() != null) {
                isLabled = true;
                labelId = fileInfo.getLabel().getId();
                labelName = fileInfo.getLabel().getName();
            }
            if (fileInfo.getProtection() != null) {
                owner = fileInfo.getProtection().getOwner();
                contentId = fileInfo.getProtection().getContentId();
                if (fileInfo.getProtection().getProtectionDescriptor() != null) {
                    isProtected = true;
                    templateId = fileInfo.getProtection().getProtectionDescriptor().getTemplateId();
                    templateName = fileInfo.getProtection().getProtectionDescriptor().getName();
                }
            }
        }
        ResponseInfo result = new ResponseInfo(0, "Success");
        result.setLabeled(isLabled);
        result.setProtected(isProtected);
        result.setCreationTime(creationTime);
        result.setContentId(contentId);
        result.setOwner(owner);
        result.setLabelId(labelId);
        result.setLabelName(labelName);
        result.setTemplateId(templateId);
        result.setTemplateName(templateName);
        result.setDispFileName(displayFileName);
        result.setFileLabelGuid(labelId);
        result.setFileProtectionGuid(templateId);
        result.setFileOwner(owner);
        result.setFileExt(AipFileUtils.getExtension(displayFileName));
        result.setFileSize(fileSize);
        return result;
    }
}
