package mobvista.dmp.main;

import mobvista.prd.datasource.util.HttpUtil;
import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Row;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UrlToName {

    public static void main(String[] args) throws Exception {
        FileOutputStream out = new FileOutputStream("/Users/fl/Desktop/url_app_name.xls");
        POIFSFileSystem pfs = new POIFSFileSystem(new FileInputStream("/Users/fl/Desktop/inventoryurl.xls"));
        HSSFWorkbook workbook = new HSSFWorkbook(pfs);
        HSSFSheet sheet = workbook.getSheetAt(0);
        Map<String, String> map = new HashMap<String, String>();
        List<String> list = new ArrayList<>();
        for (int i = 0; i < 101; i++) {
            Row row = sheet.getRow(i);
            String url = row.getCell(0).getStringCellValue();
            String appName = null;
            try {
                if (url.contains("play.google.com")) {
                    appName = getAdrAppName(url);
                } else if (url.contains("itunes.apple.com")) {
                    appName = getIosAppName(url);
                }
                map.put(url, appName);
            } catch (Exception e) {
                list.add(url);
            }
        }

        HSSFSheet sheet1 = workbook.createSheet("匹配结果");
        int i = 0;
        for (Map.Entry<String, String> entry: map.entrySet()) {
            Row row = sheet1.createRow(i);
            row.createCell(0).setCellValue(entry.getKey());
            row.createCell(1).setCellValue(entry.getValue());
            i++;
        }
        workbook.write(out);

        for (String str : list) {
            System.out.println(str);
        }
    }

    public static String getAdrAppName (String url) throws Exception {
        String result = HttpUtil.getRequest(url, null, Logger.getLogger(UrlToName.class));
        Element element = Jsoup.parse(result).select("h1[itemprop=name] div").first();
        return element.text();
    }

    public static String getIosAppName (String url) throws Exception {
        String result = HttpUtil.getRequest(url, null, Logger.getLogger(UrlToName.class));
        Element element = Jsoup.parse(result).select("h1[itemprop=name]").first();
        return element.text();
    }
}
