#!/usr/bin/env node

/* jshint esversion: 8 */
/* global describe */
/* global before */
/* global after */
/* global it */
/* global xit */

'use strict';

require('chromedriver');

const delay = require('delay'),
    execSync = require('child_process').execSync,
    expect = require('expect.js'),
    fs = require('fs'),
    path = require('path'),
    superagent = require('superagent'),
    { Builder, By, until } = require('selenium-webdriver'),
    { Options } = require('selenium-webdriver/chrome');

describe('Application life cycle test', function () {
    this.timeout(0);

    const LOCATION = 'test';
    const TEST_TIMEOUT = 30000;
    const BUCKET = 'cloudrontestbucket';
    const EXEC_ARGS = { cwd: path.resolve(__dirname, '..'), stdio: 'inherit' };

    let browser, app;

    before(function () {
        browser = new Builder().forBrowser('chrome').setChromeOptions(new Options().windowSize({ width: 1280, height: 1024 })).build();
    });

    after(function () {
        browser.quit();
    });

    async function waitForElement(elem) {
        await browser.wait(until.elementLocated(elem), TEST_TIMEOUT);
        await browser.wait(until.elementIsVisible(browser.findElement(elem)), TEST_TIMEOUT);
    }

    function getAppInfo() {
        var inspect = JSON.parse(execSync('cloudron inspect'));
        app = inspect.apps.filter(function (a) { return a.location.indexOf(LOCATION) === 0; })[0];
        expect(app).to.be.an('object');
    }

    async function login(accessKey='minioadmin', secretKey='minioadmin') {
        await browser.get(`https://${app.fqdn}/login`);
        await waitForElement(By.id('accessKey'));
        await browser.findElement(By.id('accessKey')).sendKeys(accessKey);
        await browser.findElement(By.id('secretKey')).sendKeys(secretKey);
        await browser.findElement(By.xpath('//button[@id="do-login"]')).click();
        await waitForElement(By.xpath('//span[contains(text(), "Buckets")]'));
        await delay(5000);
    }

    async function logout() {
        await browser.get(`https://${app.fqdn}/`);
        await waitForElement(By.xpath('//span[contains(text(), "Buckets")]'));
        const button = await browser.findElement(By.xpath('//div/span[contains(text(), "Sign Out")]'));
        await browser.executeScript('arguments[0].scrollIntoView(false)', button);
        await button.click();
        await waitForElement(By.id('accessKey'));
    }

    async function addBucket() {
        await browser.get(`https://${app.fqdn}/buckets`);
        await waitForElement(By.xpath('//button[@id="create-bucket"]'));
        await browser.findElement(By.xpath('//button[@id="create-bucket"]')).click();
        await browser.sleep(2000);
        await browser.findElement(By.xpath('//input[@id="bucket-name"]')).sendKeys(BUCKET);
        await browser.findElement(By.xpath('//button[@id="create-bucket"]')).click();
        await waitForElement(By.xpath(`//h1[contains(text(), "${BUCKET}")]`));
        await delay(5000);
    }

    async function checkBucket() {
        await browser.get(`https://${app.fqdn}/buckets`);
        await waitForElement(By.xpath(`//h1[contains(text(), "${BUCKET}")]`));
    }

    async function checkRedirect() {
        const response = await superagent.get(`https://${app.secondaryDomains[0].fqdn}`).set('User-Agent', 'Mozilla/5.0').redirects(0).ok(() => true);
        expect(response.status).to.be(307);
        expect(response.headers.location).to.be(`https://${app.fqdn}`);
    }

    async function checkApi() {
        const response = await superagent.get(`https://${app.secondaryDomains[0].fqdn}`).ok(() => true);
        expect(response.status).to.be(403);
        expect(response.body.toString('utf8')).to.contain('<Code>AccessDenied</Code>');
    }

    xit('build app', function () { execSync('cloudron build', EXEC_ARGS); });
    it('install app', async function () {
        execSync(`cloudron install --location ${LOCATION} --secondary-domains API_SERVER_DOMAIN=${LOCATION}-api`, EXEC_ARGS);
        await delay(10000);
    });

    it('can get app information', getAppInfo);

    it('can login', login.bind(null, 'minioadmin', 'minioadmin'));
    it('can add bucket', addBucket);
    it('can logout', logout);
    it('does redirect', checkRedirect);
    it('check api', checkApi);

    it('can change credentials', async function () {
        let data = fs.readFileSync(path.join(__dirname, '../env.sh'), 'utf8');
        data = data
            .replace(/MINIO_ROOT_USER=.*/, 'MINIO_ROOT_USER=minioakey')
            .replace(/MINIO_ROOT_PASSWORD=.*/, 'MINIO_ROOT_PASSWORD=minioskey');
        fs.writeFileSync('/tmp/env.sh', data);
        execSync(`cloudron push --app ${app.id} /tmp/env.sh /app/data/env.sh`, EXEC_ARGS);
        execSync(`cloudron restart --app ${app.id}`, EXEC_ARGS);
        await delay(10000);
    });

    it('can restart app', function () { execSync(`cloudron restart --app ${app.id}`, EXEC_ARGS); });

    it('can login', login.bind(null, 'minioakey', 'minioskey'));
    it('has bucket', checkBucket);
    it('can logout', logout);
    it('does redirect', checkRedirect);
    it('check api', checkApi);

    it('backup app', function () { execSync('cloudron backup create --app ' + app.id, EXEC_ARGS); });
    it('restore app', async function () {
        const backups = JSON.parse(execSync(`cloudron backup list --raw --app ${app.id}`));
        execSync('cloudron uninstall --app ' + app.id, EXEC_ARGS);
        execSync('cloudron install --location ' + LOCATION, EXEC_ARGS);
        getAppInfo();
        execSync(`cloudron restore --backup ${backups[0].id} --app ${app.id}`, EXEC_ARGS);
        await delay(10000);
    });

    it('can login', login.bind(null, 'minioakey', 'minioskey'));
    it('has bucket', checkBucket);
    it('can logout', logout);
    it('does redirect', checkRedirect);
    it('check api', checkApi);

    it('move to different location', async function () {
        browser.manage().deleteAllCookies();
        execSync('cloudron configure --location ' + LOCATION + '2', EXEC_ARGS);
        await delay(10000);
    });
    it('can get app information', getAppInfo);

    it('can login', login.bind(null, 'minioakey', 'minioskey'));
    it('has bucket', checkBucket);
    it('can logout', logout);
    it('does redirect', checkRedirect);
    it('check api', checkApi);

    it('uninstall app', function () { execSync('cloudron uninstall --app ' + app.id, EXEC_ARGS); });

    // test update
    it('can install app', function () { execSync('cloudron install --appstore-id io.minio.cloudronapp --location ' + LOCATION, EXEC_ARGS); });
    it('can get app information', getAppInfo);

    it('can login', login.bind(null, 'minioadmin', 'minioadmin'));
    it('can add buckets', addBucket);
    it('can logout', logout);
    it('can update', function () { execSync(`cloudron update --app ${LOCATION}`, EXEC_ARGS); });
    it('can configure', function () { execSync(`cloudron configure --app ${LOCATION} --location ${LOCATION} --secondary-domains API_SERVER_DOMAIN=${LOCATION}-api`, EXEC_ARGS); });
    it('can get app information', getAppInfo);

    it('can login', login.bind(null, 'minioadmin', 'minioadmin'));
    it('has bucket', checkBucket);
    it('can logout', logout);
    it('does redirect', checkRedirect);
    it('check api', checkApi);

    it('uninstall app', function () { execSync('cloudron uninstall --app ' + app.id, EXEC_ARGS); });
});

