const puppeteer = require('puppeteer');

const config = {
    licenseId: process.argv[2],
	username: process.argv[3],
    password: process.argv[4],
	licensePortalUrl: 'https://webtop1.sharepoint.com/sites/intranet/_layouts/15/appredirect.aspx?instance_id={E92AAB68-DA3F-4E19-A375-59326BE8D992}',
	licenseCustomerUrl: 'https://wizdomlicenseportal.azurewebsites.net/Pages/Default.aspx?SPHostUrl=https%3A%2F%2Fwebtop1%2Esharepoint%2Ecom%2Fsites%2Fintranet#!/Customers/',
	wizdomurl: 'https://webtop1.sharepoint.com/sites/intranet',
    waittime: 6000
};

const elements = {
    login: 'input[type="email"]',
    submit: 'input[type="submit"]',
    pass: 'input[name="passwd"]',
	dontRemember: '#idBtn_Back'
};

const login = async (page) => {
    await page.goto(config.wizdomurl);
    await page.waitFor(config.waittime);

    await page.type(elements.login, config.username);
    await page.click(elements.submit);
    await page.waitFor(config.waittime);

    await page.type(elements.pass, config.password);
    await page.click(elements.submit);
    await page.waitFor(config.waittime);

	await page.click(elements.dontRemember);
	await page.waitFor(config.waittime);
}


const getLicense = async (page) => {
	await page.goto(config.licensePortalUrl);
	await page.waitFor(config.waittime);
	
	await page.setRequestInterception(true);
	page.on('request', request => {
		var overrides = {
			'method': 'POST'
		}
		request.continue(overrides);
	});
	const response = await page.goto('https://wizdomlicenseportal.azurewebsites.net/api/Licenses/' + config.licenseId + '/pairingrequests?SPHostUrl=https%3A%2F%2Fwebtop1%2Esharepoint%2Ecom%2Fsites%2Fintranet');
	const responseBody = await response.text();
    console.log(responseBody);
}

puppeteer.launch({headless:true, args: ['--no-sandbox', '--disable-setuid-sandbox'] }).then(async browser => {
    const page = await browser.newPage();
    await login(page);
	await getLicense(page);
	await browser.close();
});