package com.mobvista.apptag.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * @package: com.mobvista.apptag.utils
 * @author: wangjf
 * @date: 2019-07-17
 * @time: 11:38
 * @email: jinfeng.wang@mobvista.com
 * @phone: 152-1062-7698
 */
public class GetPackageFromFile {

    public static void main(String[] args) {
        try {
            String filePath = "/home/mobdev/workspace/data/data.js";
            Set<String> set = readTxtFileIntoStringSet(filePath);
            System.out.println("packageNames.size ===>>> " + set.size());
            MySqlUtil mySqlUtil = new MySqlUtil();
            mySqlUtil.insert(set);
        } catch (Exception e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        }
    }

    public static Set<String> readTxtFileIntoStringSet(String filePath) throws ParseException {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = sdf.parse(sdf.format(date));
        Calendar rightNow = Calendar.getInstance();
        rightNow.setTime(dt);
        rightNow.add(Calendar.DAY_OF_YEAR, -7);
        Date newDate = sdf.parse(sdf.format(rightNow.getTime()));

        Set<String> set = new HashSet<>();
        try {
            String encoding = "GBK";
            File file = new File(filePath);
            //  判断文件是否存在
            if (file.isFile() && file.exists()) {
                //  考虑到编码格式
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    String str = lineTxt.replace("\"", "");
                    if (str.startsWith("result")) {
                        String[] arr = str.split("=")[1].split(",");
                        if (newDate.before(sdf.parse(arr[1]))) {
                            set.add(arr[0]);
                        }
                    }
                }
                bufferedReader.close();
                read.close();
            } else {
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return set;
    }
}
