"use strict";
// import { inject } from 'inversify';
// import { ApiClientBase } from '@codiac.io/api-client-base/api-client-base';
// import { INTERFACES } from '@codiac.io/codiac-common';
// import { IBetterLogger, LogLevel } from '@codiac.io/codiac-common/IBetterLogger';
// import { CliExec } from '@codiac.io/codiac-ops-common';
// import { SingleResult, CodiacError } from '@codiac.io/codiac-common/contracts';
// import { IClientForImageRegistry } from '../i-client-for-image-registry';
// import { ImageTagList } from '../docker-registry-api-client/entities/image-tag-list';
// /*  NOTES:
//   https://docs.microsoft.com/en-us/rest/api/containerregistry/
//   List operations in the api:
//   https://management.azure.com/providers/Microsoft.ContainerRegistry/operations?api-version=2019-05-01
// */
// /**
//  * INterface for an Azure Container Registry
//  * 
//  * @see https://docs.microsoft.com/en-us/rest/api/containerregistry/ Azure docs: Azure Container Registry REST API reference
//  * @see https://docs.microsoft.com/en-us/azure/container-registry/container-registry-authentication Azure docs: Authenticating with an ACR.
//  */
// export class AzureContainerRegistryClient extends ApiClientBase implements IClientForImageRegistry {
//   public static AZ_MGMT_BASE_URL = "https://management.azure.com";
//   // /** The full domain of the api service without the initial hostname (DOES NOT start with a period). */
//   // public static ACR_DOMAIN_BASE = "azurecr.io";
//   public static API_VERSION = "2019-05-01";  // used in querystring as:  ?api-version=2019-05-01
//   /**
//    * @param registryDomain The server host name of the registry (eg: my.registry.io) (without any url protocol). 
//    *              This value is the first part of a fully qualified image name, separated by a slash "/" character.   */
//   static supports(registryDomain: string): boolean {
//     return registryDomain.endsWith(".azurecr.io");
//   }
//   // * @param azSubscriptionId The guid for the Azure Subscription that owns the ACR.  
//   /**
//    * @param registryDomainName The fully qualified name of the ACR (eg: `mystuff.azurecr.io`), used as the first part of a fully qualified image name.  The hostname of this domain is parsed out as the resource name of the acr itself inside the azure subscription. 
//    * @param logger 
//    * @param apiRootUrl 
//    * @param authToken 
//    */
//   constructor(/* public azSubscriptionId: string, */ public registryDomainName: string, @inject(INTERFACES.ILogger) logger: IBetterLogger
//     , apiRootUrl?: string, authToken?: string) {
//     super(logger, apiRootUrl, authToken);
//     if (!registryDomainName || registryDomainName == "") throw new CodiacError(`Cannot instantiate without a registryDomainName.`);
//     this.acrResourceName = registryDomainName.split(".")[0];
//     this._cliExec = new CliExec(logger);  // this wed be better of lazy-loaded cuz we arent always gonna use it.
//     this.subxIdForRegistry = "abc123-got-this-from-imageexport-or-project";
//   }
//   private _cliExec: CliExec;
//   public acrResourceName: string;
//   public subxIdForRegistry: string;
//   protected GetDefaultRootUrl(): string {
//     return AzureContainerRegistryClient.AZ_MGMT_BASE_URL;
//   }
//   /** Ensures that the current azure subscription matches the one that owns the registry for the given image. */
//   public async setRelevantAzSubscription(subxIdForRegistry: string): Promise<void> {
//     return new Promise<void>(async (resolve, reject) => {
//       try {
//         // TIP:  When outputting a single value from an az cli command, use "-o tsv" to remove the quotes from the output. 
//         let whoami = `az account show -o json`;  // retrieves current az username
//         let azTenantUser = await this._cliExec.execAsyncJson<AzureTenantUser>(whoami, { cwd: process.cwd() }, LogLevel.debug);
//         this.logger.debug(`Current Azure user subscription: ${azTenantUser.name}, ${azTenantUser.id}`, azTenantUser);
//         // TODO:  Enforce consistency betw AZ subscriptionId for the project and the current azure account
//         if (azTenantUser.id != this.subxIdForRegistry) {
//           // let getMySubs = `az account list --query "[?id == '${subxIdForRegistry}']" -o json`;
//           // let mySubs = await this._cliExec.execAsyncJson<AzureTenantUser[]>(getMySubs, { cwd: process.cwd() }, LogLevel.debug);
//           // if (mySubs.length > 0) {
//           //   // Switch to the relevant account
//           //   let setSubx = `az account set --subscription ${subxIdForRegistry}`;  
//           //   azTenantUser = await this._cliExec.execAsyncJson<AzureTenantUser>(setSubx, { cwd: process.cwd() }, LogLevel.debug);
//           // }
//         }
//         resolve();
//       } catch (err) {
//         reject(err);
//       }
//     });
//   }
//   public async authenticate(registryDomain: string, secret: string, username?: string): Promise<boolean> {
//     return new Promise<boolean>(async (resolve, reject) => {
//       try {
//         let success = false;
//         throw new Error(`Authenticate isnt implemented yet for the Azure registry client.`);
//         success = true;
//         resolve(success);
//       } catch (err) {
//         reject(err);
//       }
//     });
//   }
//   public async push(registryDomain: string, scopedImageName: string, tag: string): Promise<void> {
//     return new Promise<void>(async (resolve, reject) => {
//       try {
//         let fullImageId = registryDomain ? `${registryDomain}/${scopedImageName}:${tag}` : `${scopedImageName}:${tag}`;
//         await this.setRelevantAzSubscription(this.subxIdForRegistry);
//         // Does this select the right az creds?  How can it?  
//         // TODO: We need to save the subscription Id with the codiac project, so we can select prevent az account mismatches.
//         //       Q: When would we gather the subscriptionId?  A: Upon image declaration (and then whenever we mod the registry for it)
//         let cmdLogin = `az acr login --name ${registryDomain.split(".")[0]}`;
//         let loginEnv: { [key: string]: any } = { ...process.env };
//         let workingDir = process.cwd();
//         // this.logger.notice(`Logging in and pushing [${this.styler.hilite(scopedImageName)}] to registry as [${this.styler.hilite(fullImageId)}]...`);
//         this.logger.notice(`Logging in and pushing [${scopedImageName}] to registry as [${fullImageId}]...`);
//         let cmdLoginAndPush = cmdLogin.concat(`  &&  docker push ${fullImageId}`);
//         await this._cliExec.spawnAndLog(cmdLoginAndPush, workingDir, loginEnv, LogLevel.detail);
//         resolve();
//       } catch (err) {
//         reject(err);
//       }
//     });
//   }
//   public async tryGetImageTags(scopedImageName: string): Promise<SingleResult<ImageTagList>> {
//     return new Promise<SingleResult<ImageTagList>>(async (resolve, reject) => {
//       let result = new SingleResult<ImageTagList>(false);
//       try {
//         // if (!registryDomainName) throw new CodiacError(`Cannot retrieve image tags for ${scopedImageName}: no registryDomainName was provided.`)
//         // let acrResourceName = registryDomainName.split(".")[0];
//         let parts: string[] = scopedImageName.split("/");
//         let scope = (parts.length > 1) ? parts[0] : undefined;  // Scope shouldnt exist on an acr image name
//         let repositoryName = parts[parts.length - 1];
//         // TODO: Move this out to a factory method or lazy-run it.
//         await this.setRelevantAzSubscription(this.subxIdForRegistry);
//         // az acr repository show-tags --repository codiac-api -n devcodiaccontainers
//         let cmd = `az acr repository show-tags --repository ${repositoryName} -n ${this.acrResourceName} -o json`;
//         let tags = await this._cliExec.execAsyncJson<string[]>(cmd, { cwd: process.cwd() }, LogLevel.debug);
//         result.output = new ImageTagList(scopedImageName, tags);
//         result.success = (result.output.tags.length > 0);
//       } catch (err) {
//         result.error = new CodiacError(`Error loading tags for [${scopedImageName}] from registry [${this.registryDomainName}]: ${err.name || ""} ${err.message || ""}`, err);
//         result.message = result.error.message;
//         this.logger.debug(result.message, result.error);
//       } finally {
//         resolve(result);
//       }
//     });
//   }
// }
// export type AzureTenantUser = {
//   "environmentName": string,
//   "id": string,
//   "isDefault": boolean,
//   "name": string,
//   "state": string,
//   "tenantId": string,
//   "user": {
//     "name": string,
//     "type": string
//   }
// };
//# sourceMappingURL=azure-container-registry-client.js.map