package com.lion.lionwebsite.Service;

import com.lion.lionwebsite.Dao.normal.CustomConfigurationMapper;

import com.lion.lionwebsite.Dao.normal.ShareFileMapper;
import com.lion.lionwebsite.Dao.normal.UserMapper;
import com.lion.lionwebsite.Domain.CustomConfiguration;
import com.lion.lionwebsite.Domain.ShareFile;
import com.lion.lionwebsite.Domain.User;
import com.lion.lionwebsite.Interceptor.TaskHandlerInterceptor;
import com.lion.lionwebsite.Util.CustomUtil;
import com.lion.lionwebsite.Util.FileDownload;
import com.lion.lionwebsite.Util.Response;

import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;

import static com.lion.lionwebsite.Util.CustomUtil.fourZeroFour;


@Service
public class PublicServiceImpl {

    @Resource
    CustomConfigurationMapper configurationMapper;

    @Resource
    ShareFileMapper shareFileMapper;

    @Resource
    UserMapper userMapper;

    @Resource
    TaskHandlerInterceptor taskHandlerInterceptor;

    public PublicServiceImpl(CustomConfigurationMapper configurationMapper, ShareFileMapper shareFileMapper, UserMapper userMapper, TaskHandlerInterceptor taskHandlerInterceptor) {
        this.configurationMapper = configurationMapper;
        this.shareFileMapper = shareFileMapper;
        this.userMapper = userMapper;
        this.taskHandlerInterceptor = taskHandlerInterceptor;
    }

    /**
     * 记录家里ip地址
     * @param ip ip地址
     */
    public void logIpAddress(String ip) {
        configurationMapper.updateConfiguration(CustomConfiguration.CURRENT_IP_ADDRESS, ip);
        configurationMapper.updateConfiguration(CustomConfiguration.LAST_UPDATE_IP_ADDRESS_TIME, CustomUtil.now());
    }

    /**
     * 通过分享码获取文件
     * @param httpRequest   请求对象
     * @param httpResponse  响应对象
     * @param ShareCode     分享码
     * @throws IOException  响应时的异常
     */
    public boolean GetFile(HttpServletRequest httpRequest, HttpServletResponse httpResponse, String ShareCode) throws IOException {
        Response response = Response.generateResponse();

        //参数为空的情况
        if(ShareCode == null) {
            response.failure("ShareCode invalid");
        } else {
            ShareFile shareFile = shareFileMapper.selectShareFileByShareCode(ShareCode);
            Calendar ExpireTime = Calendar.getInstance();
            Calendar now = Calendar.getInstance();

            if (shareFile != null) {
                ExpireTime.setTime(shareFile.getExpireTime());
                if (ExpireTime.after(now) && new File(shareFile.getFilePath()).isFile()) {
                    FileDownload.export(httpRequest, httpResponse, shareFile.getFilePath());
                    return true;
                } else {
                    shareFileMapper.deleteShareFile(shareFile.getShareCode());
                    response.failure("ShareCode is expired or File is not exist");
                }
            } else
                response.failure("ShareCode is not exist or expired");
        }

        httpResponse.getOutputStream().write(response.toJSONString().getBytes(StandardCharsets.UTF_8));
        return false;
    }

    /**
     * 修改授权码，如果能够执行此方法，则授权码一定存在
     * @param AuthCode          原来的授权码
     * @param newAuthCode       新的授权码
     * @return                  修改结果
     */
    public String alterAuthCode(String AuthCode, String newAuthCode) {
        Response response = Response.generateResponse();

        userMapper.updateAuthCode(AuthCode, newAuthCode);
        taskHandlerInterceptor.updateAuthCodes();
        response.success("修改成功");

        return response.toJSONString();
    }

    public User getUserId(String AuthCode){
        return userMapper.selectUserByAuthCode(AuthCode);
    }

    public void getEhThumbnail(String path, HttpServletResponse response){
        String url;
        if(!path.contains("/")){
            fourZeroFour(response);
            return;
        }

        url = "https://ehgt.org/" + path;
        try{
            byte[] imageBytes = getImageBytesFromUrl(url);
            ServletOutputStream outputStream = response.getOutputStream();
            outputStream.write(imageBytes);
            outputStream.close();
        }catch (IOException | URISyntaxException e){
            e.printStackTrace();
            try {
                response.sendError(503);
            }catch (IOException ex){
                ex.printStackTrace();
            }
        }
    }

    public static byte[] getImageBytesFromUrl(String imageUrl) throws IOException, URISyntaxException {
        URL url = new URI(imageUrl).toURL();
        InputStream inputStream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            // 打开URL连接
            inputStream = url.openStream();

            byte[] buffer = new byte[1024];
            int bytesRead;
            // 从输入流读取数据并写入输出流
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        } finally {
            // 关闭流
            if (inputStream != null) {
                inputStream.close();
            }
            outputStream.close();
        }

        // 返回图片的字节数组
        return outputStream.toByteArray();
    }
}
