package ru.yandex.canvas.service.video;

import ru.yandex.canvas.model.stillage.StillageFileInfo;
import ru.yandex.canvas.model.video.VideoFiles;
import ru.yandex.canvas.repository.video.VideoFilesRepository;

public abstract class FileUploadService<P> {
    protected final VideoFilesRepository videoFilesRepository;

    public FileUploadService(VideoFilesRepository videoFilesRepository) {
        this.videoFilesRepository = videoFilesRepository;
    }

    protected abstract void beforeInsert(VideoFiles record, StillageFileInfo info, P parsedMetaData, Long presetId);

    protected abstract void afterInsert(VideoFiles record);

    abstract P parseMetaData(StillageFileInfo info);

    protected abstract void validate(P imageInfo, StillageFileInfo fileInfo,
                                     VideoCreativeType videoCreativeType, Long presetId,
                                     Long clientId);

    private static void setStillageData(VideoFiles record, StillageFileInfo info) {
        record.setStillageFileInfo(info);
        record.setUrl(info.getUrl());
        record.setStillageId(Long.valueOf(info.getId()));
    }

    public VideoFiles upload(VideoFiles record, StillageFileInfo info, Long presetId) {

        setStillageData(record, info);

        P parsedMetadata = parseMetaData(info);
        validate(parsedMetadata, info, record.getCreativeType(), presetId, record.getClientId());
        beforeInsert(record, info, parsedMetadata, presetId);

        VideoFiles updatedRecord = videoFilesRepository.save(record);

        afterInsert(updatedRecord);

        return updatedRecord;
    }

}
