package com.lion.lionwebsite.Service;

import com.lion.lionwebsite.Dao.CustomConfigurationMapper;
import com.lion.lionwebsite.Dao.GalleryMapper;
import com.lion.lionwebsite.Dao.ShareFileMapper;
import com.lion.lionwebsite.Domain.CustomConfiguration;
import com.lion.lionwebsite.Domain.ShareFile;
import com.lion.lionwebsite.Util.CustomUtil;
import lombok.Data;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static java.nio.file.FileVisitResult.CONTINUE;

@Service
@Data
public class LocalServiceImpl{
    String fires = "https://api.dler.io/sub?target=clash&new_name=true&url=https%3A%2F%2Ffast.losadhwselfff2332dasd.xyz%2Flink%2Fz0pfwyTvC5naXkbb%3Fclash%3D1&insert=false&config=https%3A%2F%2Fraw.githubusercontent.com%2FACL4SSR%2FACL4SSR%2Fmaster%2FClash%2Fconfig%2FACL4SSR_Online.ini";

    String DouNaiClash = "https://aaaa.gay/link/X7zEqkIx5gtIGugO?client=clashmeta";

    String DouNaiV2ray = "https://aaaa.gay/link/X7zEqkIx5gtIGugO?client=v2";

    CustomConfigurationMapper configurationMapper;

    ShareFileMapper shareFIleMapper;

    GalleryMapper galleryMapper;

    public LocalServiceImpl(CustomConfigurationMapper configurationMapper, ShareFileMapper shareFileMapper, GalleryMapper galleryMapper){
        this.shareFIleMapper = shareFileMapper;
        this.configurationMapper = configurationMapper;
        this.galleryMapper = galleryMapper;
    }

    /**
     * 每周周一四点重置额度
     */
    @Scheduled(cron = "0 0 4 * * MON")
    public void reset() {
        configurationMapper.updateConfiguration(CustomConfiguration.WEEK_USED_AMOUNT, "0");
        configurationMapper.updateConfiguration(CustomConfiguration.LAST_RESET_AMOUNT_TIME, CustomUtil.now());
    }

    /**
     * 定时更新订阅
     * @throws IOException 下载以及保存异常
     */
    @Scheduled(fixedRate = 86400000)
    public void updateSubScheduler() throws IOException {
        updateSub(false);
    }

    /**
     * 更新订阅链接的实际方法
     */
    public boolean updateSub(boolean isManual) throws IOException {
        DateTimeFormatter dateTimeFormatter = CustomUtil.dateTimeFormatter();
        CustomConfiguration customConfiguration = configurationMapper.selectConfiguration(CustomConfiguration.LAST_UPDATE_SUB_TIME);

        //如果不是手动，则判断更新间隔是否满足，不满足则取消更新
        if (!isManual) {
            LocalDateTime lastUpdate = LocalDateTime.parse(customConfiguration.getValue(), CustomUtil.dateTimeFormatter());
            LocalDateTime now = LocalDateTime.now();
            now = now.plusHours(-3);
            if(now.isBefore(lastUpdate))
                return false;
        }

        File mixin = new File("sub/sub.txt");
        File firesFile = new File("sub/fires.txt");
        File DouNaiClashFile = new File("sub/DouNaiClash.txt");
        File DouNaiV2rayFile = new File("sub/DouNaiV2ray.txt");
        File directory = new File("sub");

        if(!directory.isDirectory())
            Files.createDirectory(Paths.get("sub"));

        List<String> fires_profile = null;
        List<String> DouNaiClash_profile = null;
        OutputStream outputStream;

        //下载薯条订阅
        try(FileWriter writer = new FileWriter(firesFile)) {
            fires_profile = Get(fires);
            for (String i : fires_profile)
                writer.write(i + "\n");

            System.out.println("load fires complete");
        }catch (IOException e) {
            e.printStackTrace();
            System.out.println("load fires failure");
        }

        //下载豆奶v2ray订阅
        try(FileWriter writer = new FileWriter(DouNaiV2rayFile)) {
            String DouNaiV2rayRaw = Get(DouNaiV2ray).get(0);
            String[] v2rayPlain = new String(Base64.getDecoder().decode(DouNaiV2rayRaw)).split("\n");
            StringBuilder stringBuilder = new StringBuilder();
            //过滤高倍率节点
            for(String node: v2rayPlain){
                String name = URLDecoder.decode(node.split("#")[1], StandardCharsets.UTF_8);
                if(name.startsWith("①") && name.contains("流量")){
                    float ratio = Float.parseFloat(name.substring(name.indexOf("(") + 1, name.indexOf(")")).replace("倍流量", ""));
                    if(ratio <= 1)
                        stringBuilder.append(node).append("\n");
                }
                else{
                    stringBuilder.append(node).append("\n");
                }
            }
            writer.write(new String(Base64.getEncoder().encode(stringBuilder.toString().getBytes(StandardCharsets.UTF_8))));

            System.out.println("load DouNai v2ray complete");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("load DouNai v2ray failure");
        }

        //下载豆奶clash订阅
        try(FileWriter writer = new FileWriter(DouNaiClashFile)) {
            DouNaiClash_profile = Get(DouNaiClash);
            //过滤高倍率节点
            ArrayList<String> clashProcessed = new ArrayList<>();
            boolean isProxies = false;
            boolean skip = false;
            for(String line: DouNaiClash_profile){
                if(line.equals("proxies:"))
                    isProxies = true;
                else if(line.equals("proxy-groups:") && isProxies)
                    isProxies = false;

                if(isProxies) {
                    if (line.contains("name"))
                        skip = line.contains("流量");
                    if (!skip)
                        clashProcessed.add(line);
                }
                else
                    if (!line.contains("流量"))
                        clashProcessed.add(line);
            }

            for(String line: clashProcessed)
                writer.write(line + "\n");
            System.out.println("load DouNai clash complete");
        }catch (IOException e){
            e.printStackTrace();
            System.out.println("load DouNai clash failure");
        }

        //处理合并
        assert DouNaiClash_profile != null;
        int side_start = DouNaiClash_profile.indexOf("proxies:");
        int side_end = DouNaiClash_profile.indexOf("proxy-groups:");

        List<String> side_proxy = new ArrayList<>();
        List<String> side_name = new ArrayList<>();
        for (int i = side_start + 1; i < side_end; i++) {
            side_proxy.add(DouNaiClash_profile.get(i));
            if (DouNaiClash_profile.get(i).contains("name"))
                side_name.add(DouNaiClash_profile.get(i).replace("name:", ""));
        }

        List<String> final_profile = new ArrayList<>();
        assert fires_profile != null;
        for (String i : fires_profile) {
            if (i.equals("proxy-groups:"))
                final_profile.addAll(side_proxy);

            final_profile.add(i);
            if (i.equals("proxy-groups:")) {
                final_profile.add("  -");
                final_profile.add("    name: e站流量");
                final_profile.add("    type: select");
                final_profile.add("    proxies:");
                for (String x : side_name)
                    final_profile.add("     " + x);

            }
            if (i.equals("rules:"))
                final_profile.add(" - DOMAIN-KEYWORD,hentai,e站流量");
        }

        outputStream = Files.newOutputStream(mixin.toPath());
        for(String i: final_profile)
            outputStream.write((i + "\n").getBytes(StandardCharsets.UTF_8));
        outputStream.close();

        configurationMapper.updateConfiguration(CustomConfiguration.LAST_UPDATE_SUB_TIME, dateTimeFormatter.format(LocalDateTime.now()));
        return true;
    }

    /**
     * 封装好的get方法
     * @param url               url
     * @return                  请求结果
     * @throws IOException      网络异常
     */
    public static ArrayList<String> Get(String url) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse httpResponse;
        HttpGet httpGet = new HttpGet(url);

        httpResponse = httpClient.execute(httpGet);

        HttpEntity responseEntity = httpResponse.getEntity();
        int statusCode = httpResponse.getStatusLine().getStatusCode();
        ArrayList<String> temp = new ArrayList<>();

        if (statusCode == 200) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
            String str;
            while ((str = reader.readLine()) != null)
                temp.add(str);
        }

        httpClient.close();
        httpResponse.close();
        return temp;
    }

    /**
     * 每天四点，清理过期分享码
     */
    @Scheduled(cron = "0 0 4 * * *")
    public void checkShareCode(){
        ShareFile[] shareFiles = shareFIleMapper.selectAllShareFile();
        Calendar now;
        Calendar expireTime;
        for(ShareFile shareFile: shareFiles){
            now = Calendar.getInstance();
            expireTime = Calendar.getInstance();
            expireTime.setTime(shareFile.getExpireTime());
            if(now.after(expireTime))
                shareFIleMapper.deleteShareFile(shareFile.getShareCode());
        }
    }

    /**
     * 每周，查看缩略图数量，按照访问时间排序，删除超出1w的部分
     */
    @Scheduled(cron = "0 0 4 1 * *")
    public void clearThumbnailCache(){
        String cachePath = "/storage/hentaiCache/";
        File directory = new File(cachePath);
        List<Path> files = new ArrayList<>();
        try {
            Files.walkFileTree(directory.toPath(), new SimpleFileVisitor<>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    if (attrs.isRegularFile()) {
                        files.add(file);
                    }
                    return CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        files.sort((f1, f2) -> {
            try {
                return Files.readAttributes(f1, BasicFileAttributes.class).lastAccessTime()
                        .compareTo(Files.readAttributes(f2, BasicFileAttributes.class).lastAccessTime());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        });

        if (files.size() > 10000) {
            List<Path> toDelete = files.subList(0, files.size() - 10000);
            for (Path file : toDelete) {
                try {
                    Files.delete(file);
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            System.out.println("Deleted " + toDelete.size() + " files");
        } else {
            System.out.println("No files to delete");
        }
    }
}
