import * as chai from 'chai';
import * as request from "request-promise-native";
import 'mocha';

const expect = chai.expect;

const TEST_URL = process.env.TEST_URL || 'http://localhost:8080'

interface Test {
  request: request.OptionsWithUri;
  expect: {
    status: number;
    headers?: {};
    type?: string;
  }
  rejection?: any;
  response?: request.FullResponse;
}


let tests: Test[] = [
  {
    request: {method: 'POST', uri: '/'},
    expect: {status: 405}
  },
  {
    request: {method: 'GET', uri: '/'},
    expect: {status: 404}
  },
  // Why are these public?
  // {
  //   request: {method: 'GET', uri: '/maps/auth-preload.js.076e6eae83dcf1ae957de9794f463b44.map'},
  //   expect: {status: 404}
  // },
  {
    request: {method: 'GET', uri: '/assets/Amazon.Fuel.Common.dll.cadc5536d4e45f91a8f88377e86f2eb8c36ed71b.bundle'},
    expect: { status: 200, headers: {'cache-control': 'public, max-age=31536000, immutable'}}
  },
  {
    request: {method: 'GET', uri: '/assets/Twitch%20Helper%20(GPU).b7a2ff67d2bcf8d996162710b3cb3b4041a48e62.bundle'},
    expect: { status: 200, headers: {'cache-control': 'public, max-age=31536000, immutable'}}
  },
]


for (const test of tests) {
  test.request.baseUrl = TEST_URL;
  test.request.resolveWithFullResponse = true;
  test.request.followRedirect = false;
  test.request.simple = false;

  describe(`${test.request.method} ${test.request.uri}`, () => {

    before ('should load', async () => {
      return request(test.request).then(r => {
        test.response = r;
      });
    });


    it('should have status ' + test.expect.status, () => {
      expect(test.response.statusCode).to.equal(test.expect.status)
    });


    if (test.expect.type) {
      it('should have content type ' + test.expect.type, () => {
        let s = test.response.headers['content-type']
        let mediaType = s.indexOf(';') === -1 ? s : s.substr(0, s.indexOf(';'))
        expect(mediaType).to.equal(test.expect.type)
      });
    }

    if (test.expect.headers) {
      it('should have headers ' + Object.entries(test.expect.headers).map(a => a.join(':')).join(', '), () => {
        for (const [k,v] of Object.entries(test.expect.headers)) {
        let s = test.response.headers[k]
        expect(s).to.equal(test.expect.headers[k])
        }
      });
    }

  });
}