package com.koobietech.eas.service.impl;

import com.koobietech.eas.common.constant.FileType;
import com.koobietech.eas.common.constant.FileTypeExt;
import com.koobietech.eas.common.utils.FileManager;
import com.koobietech.eas.common.utils.StudentArchiveGenerator;
import com.koobietech.eas.dao.dto.ArchivesDto;
import com.koobietech.eas.service.EasArchivesFilesService;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.util.Date;

@Service
public class EasArchivesFilesServiceImpl implements EasArchivesFilesService {

    @Value("${project.path}")
    String archivesSavePath;

    @Resource
    FileManager fileManager;

    String separator = File.separator;

    @Override
    public ArchivesDto getArchiveStudentsFile(String studentNumber) {
        return null;
    }

    @Override
    public ArchivesDto saveArchiveAttendanceFile(String studentNumber, XWPFDocument document) {
        String archiveCode = StudentArchiveGenerator.generateArchiveCode(studentNumber, FileType.XLSX.getValue());
        String path = getArchivePath(studentNumber, archiveCode);
        if ( fileManager.isFileExists(path) ) {
            fileManager.moveFile( path,  path + (new Date()).getTime() + ".back", true );
        }
        boolean status = fileManager.saveDocument(document, path);
        return new ArchivesDto(path, status, archiveCode);
    }

    private String getArchivePath(String studentNumber, String archiveCode) {
        return archivesSavePath + separator + studentNumber
                + separator + archiveCode + FileTypeExt.XLSX.getValue();
    }

    @Override
    public ArchivesDto saveArchiveScoresFile(String studentNumber, XWPFDocument document) {
        return null;
    }

    @Override
    public ArchivesDto saveArchiveStudentsFile(String studentNumber, XWPFDocument document) {
        String archiveCode = StudentArchiveGenerator.generateArchiveCode(studentNumber, FileType.DOCX.getValue());
        String path = getArchivePath(studentNumber, archiveCode);
        boolean status = fileManager.saveDocument(document, path);
        return new ArchivesDto(path, status, archiveCode);
    }

    @Override
    public ArchivesDto saveArchiveFile(String studentNumber, InputStream stream, String type) {
        return null;
    }

    @Override
    public FileInputStream getArchiveFile(String filePath) {
        return  fileManager.getArchiveFile(filePath);
    }

    @Override
    public InputStream getResourceStream(String filePath) {
        InputStream resourceAsStream = null;
        try {
            resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(filePath);
        } catch (Exception e) {}
        return resourceAsStream;
    }

    @Override
    public boolean deleteArchiveFile(String filePath) {
        return fileManager.deleteFile(filePath);
    }
}
