import * as AWS from "aws-sdk";
import * as fs from "fs";
import * as glob from "glob";
import * as fetch from "isomorphic-fetch";
import * as path from "path";
import * as pkg from "../../package.json";
import { S3Uploader } from "../classes/uploader";

// Stand up s3 and base variables
const s3 = new AWS.S3();
const s3Bucket = "static-asset";
const baseKey = "dotcom-core";
const version = pkg.version;
const libDir = "lib";

// Create an instance of the uploader
const uploader = new S3Uploader();

// Grab built files from the lib directory
const files = glob.sync(`${libDir}/**/*.?(css|html|js|map)`);

// Generate a list of keys and contents to upload
const keys: Array<[string, string]> = files.map((filename) => {
  const filePath = path.join(process.cwd(), filename);
  const basename = path.relative(path.join(process.cwd(), libDir), filename);
  const body = fs.readFileSync(filePath).toString();
  const key = `${baseKey}/${version}/${basename}`;

  return [key, body];
});

// Perform the upload
const promises = keys.map(([key, body]) => uploader.upload({ key, body }));

// Create a version.json file based on what's in the package.json
const componentsKey = `${baseKey}/version.json`;
const componentsBody = JSON.stringify({
  version,
});

Promise.all([
  ...promises,
  uploader.upload({
    key: componentsKey,
    body: componentsBody,
  }),
])
.then(async (results) => {
  // tslint:disable-next-line:no-console
  console.log(`Uploaded ${results.length} files to s3.`);

  // Everything is uploaded, now just purge fastly cache in case this is an override of an existing version
  const purges = [...keys, [componentsKey, ]].map(([key]) => {
    const url = `https://assets.staticlp.com/${key}`;
    // tslint:disable-next-line:no-console
    console.log(`Purging ${url}.`);

    return fetch(url, {
      method: "PURGE",
    });
  });
  const responses = await Promise.all(purges);
  const messages = await Promise.all(responses.map((r) => r.json()));
  const oks = messages.filter(m => m.status === "ok").length;

  // tslint:disable-next-line:no-console
  console.log(`Done.`);
})
.catch((error) => {
  // tslint:disable-next-line:no-console
  console.error(error);

  process.exit(1);
});
