package com.example.config;

import com.example.frame.utils.IDgenerator;
import com.example.module.admin.ent.Mapping;
import com.example.module.admin.ent.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.util.StringUtils;
import xyz.wbsite.wsqlite.ObjectClient;
import xyz.wbsite.wsqlite.Where;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


@Configuration
public class SqliteConfig {
    @Autowired
    public Environment environment;

    @Bean
    public ObjectClient registry() {
        try {
            String dbpath = environment.getProperty("dbpath");
            if (StringUtils.isEmpty(dbpath)) {
                ApplicationHome home = new ApplicationHome(getClass());
                // 当前运行jar文件
                File jarFile = home.getSource() != null ? home.getSource() : home.getDir();
                //jar同目录
                dbpath = jarFile.getParent();
            }

            ArrayList<Class> objects = new ArrayList<>();
            objects.add(Mapping.class);
            objects.add(Service.class);
            ObjectClient objectClient = new ObjectClient(new File(dbpath, "data.db"), objects);

            List<Service> select = objectClient.select(Service.class, Where.builder().build(),1, 1);
            if (select.size() == 0 && objectClient.insert(Service.class, new Service(IDgenerator.nextId(), "8888", "默认端口")) != 1) {
                throw new RuntimeException("Nginx default port 8888 init failed.");
            }

            return objectClient;
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
