/*
 * @Author: Kane
 * @Date: 2022-04-22 10:53:49
 * @LastEditors: Kane
 * @LastEditTime: 2022-05-10 16:28:07
 * @FilePath: \DisasterWarning\src\main\java\AppMain.java
 * @Description: 和风天气预警推送厦门太保公众号主程序！
 * 
 * Copyright (c) ${2022} by Kane, All Rights Reserved. 
 */
import com.cpic.xim.config.AppConfigManager;
import com.cpic.xim.config.City;
import com.cpic.xim.notify.disaster.QWeatherDisasterWarning;
import com.cpic.xim.notify.disaster.WeatherDisasterWarningGrabber;
import com.cpic.xim.wechat.officalAccount.sendMessage;
import com.cpic.xim.config.WeatherDisasterNotifyConfig;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Vector;
import java.util.logging.*;


public class AppMain
{
    // private final static String LOG_FILE_PATH = "./logs/app%u.log";

    public static void main( String[] args )
    {
        String json;
        WeatherDisasterNotifyConfig config = null;
        QWeatherDisasterWarning warning = null;
        Logger logger = null;

        // 配置logger
        try
        {
            setRootLogger();

            logger = Logger.getLogger( "com.cpicxim" );
        }
        catch ( IOException error )
        {
            System.out.println( "配置logger失败，原因：" + error.getMessage() );

            return;
        }

        // 读取配置
        try
        {
            config = AppConfigManager.getConfig();
        }
        catch ( IOException error )
        {
            System.out.println( "读取配置文件失败！" );
            System.out.println( error.getMessage() );

            logger.log( Level.SEVERE, "读取配置文件失败：{0}", error.getMessage() );

            return;
        }

        Vector<City> cities = config.getCities();
        String queryURL = config.getQueryUrl();
        String userKey = config.getKey();

        // 遍历所有城市，查询是否有警报，有则推送。
        while (true)
        {
            for ( City city : cities )
            {
                try
                {
                    json = WeatherDisasterWarningGrabber.getWeatherDisasterWarningJSON( queryURL,
                            userKey, city.getCityCode() );
                    warning = WeatherDisasterWarningGrabber.convertWeatherDisasterWarning( json );

                    logger.log( Level.INFO, "查询{0}天气预警，结果：{1}。", new Object[]
                    { city.getCityName(), json} );

                    // 判断是否有警报
                    if ( warning.getWarning().isEmpty() == true)
                    {
                        logger.log( Level.INFO, "查询{0}天气预警，无警报！。", new Object[]
                        { city.getCityName()} );
                        continue;
                    }

                    logger.log( Level.INFO, "查询{0}天气预警，发送日志。", new Object[]
                    { city.getCityName()} );

                    sendMessage.sendWeatherDisasterWarning( config.getWechatOfficalAccountURL(),
                            warning );

                    logger.log( Level.INFO, "{0}天气预警，日志发送成功。", new Object[]
                    { city.getCityName()} );

                    sendMessage.saveWeatherDisasterWarning( city.getCityName(), warning );
                }
                catch ( IOException error )
                {
                    System.out.println( "查询" + city.getCityName() + "出现异常！" );
                    System.out.println( error.getMessage() );

                    logger.log( Level.SEVERE, "查询 {0} 出现异常:{1}。", new Object[]
                    { city.getCityName(), error.getMessage()} );
                }
                catch ( SQLException error )
                {
                    logger.log( Level.SEVERE, "查询 {0} 写入数据库失败:{1}。", new Object[]
                    { city.getCityName(), error.getMessage()} );
                }
                catch ( ClassNotFoundException error )
                {
                    logger.log( Level.SEVERE, "查询 {0} 加载oracle驱动失败:{1}。", new Object[]
                    { city.getCityName(), error.getMessage()} );

                }
                catch ( Exception error )
                {
                    logger.log( Level.SEVERE, "查询 {0} 出现未知错误:{1}。", new Object[]
                    { city.getCityName(), error.getMessage()} );
                }
            }

            try
            {
                logger.log( Level.INFO, "查询结束，休眠{0}分钟。", config.getQueryInterval() );
                Thread.sleep( config.getQueryInterval() * 1000 * 60 );
            }
            catch ( InterruptedException error )
            {
                logger.log( Level.SEVERE, "线程休眠异常，错误信息:{0}", new Object[]
                { error.getMessage()} );
            }
        }
    }

    /**
     * 设置JUL的logger。
     */
    private static void setRootLogger() throws IOException
    {
        LogManager logManager = LogManager.getLogManager();
        // 使用外部的配置文件。
        FileInputStream configFile = new FileInputStream( "./logging.properties" );
        // 使用jar中的配置文件。
        // InputStream configFile =
        // AppMain.class.getClassLoader().getResourceAsStream( "logging.properties" );

        logManager.readConfiguration( configFile );

        Logger.getLogger( "com.cpicxim" );
    }
}
