package com.zjty.autotest.util;

import com.zjty.autotest.common.action.Browser;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Objects;

public class WebDriverUtil {

    private static final Logger logger = LoggerFactory.getLogger(WebDriverUtil.class);
    /* 公共的 */
    public final static String CHROME_EXE = System.getProperty("user.dir") + File.separator+"chromedriver";

    public final static String FIRE_FOX_EXE = System.getProperty("user.dir") +File.separator+ "geckodriver";

    public final static String IE_EXE = System.getProperty("user.dir") +File.separator+ "IEDriverServer.exe";


    public static WebDriver getWebDriver(String browser) {
        if (Objects.equals(browser, Browser.FIREFOX)) {
            System.setProperty("webdriver.firefox.driver", WebDriverUtil.FIRE_FOX_EXE);
            return new FirefoxDriver();
        } else if (Objects.equals(browser, Browser.CHROME)) {
            System.setProperty("webdriver.chrome.driver", WebDriverUtil.CHROME_EXE);
            return new ChromeDriver();
        } else if (Objects.equals(browser, Browser.IE)) {
            System.setProperty("webdriver.ie.driver", WebDriverUtil.IE_EXE);
            return new InternetExplorerDriver();
        } else {
            throw new RuntimeException("该浏览器不存在：" + browser);
        }
    }

    /**
     * 结束所有残留进程
     *
     * @param
     */
    public static void killSelenium() {
        String[] pss = new String[]{
                "chromedriver*",// google驱动
                "IEDriver*",// IE 驱动
                "geckodriver*",// Firefox 驱动
                "operadriver*"// opera 驱动
        };
        for (String p1 : pss) {
            kill_process(p1);
        }
    }

    /**
     * 结束残留进程
     *
     * @param s
     */
    public static void kill_process(String s) {
        try {
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("taskkill /f /t /im " + s);
        } catch (Exception e) {
            logger.error("结束进程失败！进程名：" + s + "" + e.getMessage(), e);
        }
    }

    /**
     * 获取当前日期和时间
     *
     * @return
     */
    public static String getNowDateTimeByFormat(String formatString) {
        if (null == formatString) {
            formatString = "yyyy-MM-dd HH:mm:ss";
        }
        return new SimpleDateFormat(formatString).format(new Date());
    }
}
