package com.ffii.core.user.service;

import java.io.IOException;
import java.util.Map;
import java.util.Optional;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.ffii.core.common.file.FileRefType;
import com.ffii.core.common.file.service.FileService;
import com.ffii.core.support.AbstractService;
import com.ffii.core.support.JdbcDao;

@Service
public class UserSignService extends AbstractService {

  private FileService fileService;

  public UserSignService(JdbcDao jdbcDao,FileService fileService) {
    super(jdbcDao);
    this.fileService = fileService;
  }

  public Optional<Map<String, Object>> findUserSignatureMap(int userId) {
    return jdbcDao.queryForMap(
        "SELECT" +
            " fr.refId," +
            " fr.created," +
            " fb.bytes" +
            " FROM file_ref fr" +
            " LEFT JOIN files_blob fb ON fr.fileId = fb.fileId" +
            " WHERE fr.refId = :userId" +
            " AND fr.refType = :refType" +
            " order by fr.fileId desc" +
            " limit 1",
        Map.of("userId", userId, "refType", FileRefType.USER_SIGN));
  }

  @Transactional(rollbackFor = Exception.class)
  public void saveSign(int userId, MultipartFile userSign) throws IOException {
    String filename = String.format("%d_%s", System.currentTimeMillis(), FileRefType.USER_SIGN);
    fileService.upload(userId, FileRefType.USER_SIGN,null, userSign,filename + ".png",null);
  }
}
