import * as fs from 'fs';
import {createReadStream, PathLike} from 'fs';
import {google} from 'googleapis';
import {JWT} from 'google-auth-library';

const showUsage = function () {
    console.log('Usage: <script> <upload track> <versionCode> <version status> <version Name> <version Notes> <aab bundle path>');
    console.log('track: upload track (alpha/beta/production');
    console.log('versionCode: interger version code');
    console.log('version status: completed or draft');
    console.log('version name: The version name (ex: 6.0)');
    console.log('version Note: release notes');
    console.log('bundle path: path to the .aab bundle file');
    console.log('env: GOOGLE_APPLICATION_CREDENTIALS: path to the api key  (json)');
};

if (process.argv.length < 6) {
    showUsage();
    process.exit(1);
}
const uploadTrack = process.argv[2];
const versionCode = process.argv[3];
const versionStatus = process.argv[4];
const versionName = process.argv[5];
const versionDetails = process.argv[6];
const aabFilePath = process.argv[7];
if (versionCode == null || versionCode.length < 1 || versionStatus == null || versionDetails == null || versionDetails.length < 1) {
    showUsage();
    process.exit(1);
}

try {
  const packageName = 'comptaplan.app';
  // const apkMime = 'application/vnd.android.package-archive';
  const apkMime = 'application/octet-stream';
  const apkFileStream = createReadStream(aabFilePath);
  const appName = `My comptaplan`;

  const apiKeyFilePath: PathLike = process.env.GOOGLE_APPLICATION_CREDENTIALS;
  // Use GOOGLE_APPLICATION_CREDENTIALS to point to api key (json)
  console.log(`Releasing apk for ${appName} ${versionName} (build ${versionCode} "${versionDetails}") on track ${uploadTrack} using api key at ${apiKeyFilePath}`);

  const apiKeyFile = fs.readFileSync(apiKeyFilePath, {
      encoding: 'utf-8'
  });
  const apiKeyJson = JSON.parse(apiKeyFile);

  // const authClient = auth.fromAPIKey(apiKeyFile);
  const authClient = new JWT(
      apiKeyJson.client_email,
      null,
      apiKeyJson.private_key,
      [' https://www.googleapis.com/auth/androidpublisher'],
  );

  const android = google.androidpublisher({
      version: 'v3',
      auth: authClient,
  });
  android.edits.insert({
      packageName: packageName,
  }).then(r => {
      const editId = r.data.id;
      console.log('Created edit ' + editId);

      const uploadMedia = {
          mimeType: apkMime,
          body: apkFileStream,
      };
      return android.edits.bundles.upload({
          editId: editId,
          packageName: packageName,
          media: uploadMedia,
      }, {
          headers: {
              'content-type': apkMime,
          },
      }).then(r1 => {
          const apk = r1.data;
          console.log(`Uploaded apk version ${apk.versionCode}`);

          return android.edits.tracks.update({
              editId: editId,
              packageName: packageName,
              track: uploadTrack,
              requestBody: {
                  track: uploadTrack,
                  releases: [
                      {
                          name: versionName,
                          versionCodes: [
                              versionCode
                          ],
                          status: versionStatus,
                          releaseNotes: [{
                              language: 'fr-FR',
                              text: versionDetails
                          }]
                      }
                  ]
              }
          });
      }).then(r2 => {
          const track = r2.data;
          console.log(`Update track ${track.track}`);

          return android.edits.commit({
              editId: editId,
              packageName: packageName,
          });
      }).then(r3 => {
          const committedEdit = r3.data;
          console.log('Committed edit ' + committedEdit.id);
      });
  }).catch(e => {
      console.error(e);
      process.exit(1);
  });
} catch (e) {
  console.error(e);
  process.exit(1);
}