package com.platform.listener;

import java.io.File;
import java.util.Date;

import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ClassUtils;

import com.platform.common.utils.FileUtils;
import com.platform.modules.video.constants.VideoTypeEnum;
import com.platform.modules.video.entity.VideoEntity;
import com.platform.modules.video.service.RealPathResolver;
import com.platform.modules.video.service.VideoService;
import com.platform.modules.video.util.VideoUtils;

/**
 * 具体监听处理
 *
 * @author yikaihong
 */
@Component
public class VideoFileListener implements FileAlterationListener {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private RealPathResolver realPathResolver;

    @Autowired
    private VideoFileProperties videoFileProperties;

    @Autowired
    private VideoService videoService;

    private static final String BASE_PATH = ClassUtils.getDefaultClassLoader().getResource("").getPath().substring(1) + File.separator +"static/";

    private static final String POINT = ".";

    private static final String DEFAULT_TILLE = "无标题";

    private static final String DEFAULT_CREATE_METHOD = "快手视频下载";

    @Override
    public void onFileCreate(File file) {
        if (!VideoTypeEnum.isVideo(FileUtils.getSuffix(file))) {
            logger.info("不是视频格式");
            return;
        }
        String newFileName = FileUtils.createFileName() + POINT + FileUtils.getSuffix(file);
        String serverVideoPath = videoFileProperties.getBaseSavePath() + File.separator + VideoUtils.getDateDir() + File.separator + newFileName; // 存放在服务器地址
        String newFilePath = FileUtils.BASE_PATH + File.separator + serverVideoPath;
        FileUtils.copy(file, newFilePath);
        VideoEntity videoEntity = new VideoEntity();
        videoEntity.setDate(new Date());
        videoEntity.setFileSize(VideoUtils.getFileSize(file, null));// 文件大小
        videoEntity.setDurationTime(VideoUtils.getPlayTime(file, null)); // 文件时长
        videoEntity.setTitle(DEFAULT_TILLE);
        videoEntity.setCreateMethod(DEFAULT_CREATE_METHOD);
        videoEntity.setServerVideoPath(serverVideoPath);
        videoService.insert(videoEntity);
    }


    @Override
    public void onStart(FileAlterationObserver observer) {
    }

    @Override
    public void onDirectoryCreate(File directory) {
    }

    @Override
    public void onDirectoryChange(File directory) {
    }

    @Override
    public void onDirectoryDelete(File directory) {
    }


    @Override
    public void onFileChange(File file) {
    }

    @Override
    public void onFileDelete(File file) {
    }

    @Override
    public void onStop(FileAlterationObserver observer) {
    }

}
