// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import { CustomElement } from 'chrome://resources/js/custom_element.js';
import { BrowserProxy } from './browser_proxy.js';
import * as utils from './connectors_utils.js';
import { getTemplate } from './managed_client_certificate.html.js';
export class ManagedClientCertificateElement extends CustomElement {
    static get is() {
        return 'managed-client-certificate';
    }
    static get template() {
        return getTemplate();
    }
    get pageHandler() {
        return BrowserProxy.getInstance().handler;
    }
    set policyEnabledLevels(policyLevels) {
        if (policyLevels.length === 0) {
            this.setValueToElement('#policy-enabled-levels', 'None');
            return;
        }
        this.setValueToElement('#policy-enabled-levels', `${policyLevels}`);
    }
    get managedIdentitiesSection() {
        return this.$('#managed-identities');
    }
    constructor() {
        super();
        this.fetchClientCertificateValues();
    }
    fetchClientCertificateValues() {
        this.pageHandler.getClientCertificateState().then((response) => this.updateState(response?.state), err => console.error(`Failed to fetch client cert state: ${JSON.stringify(err)}`));
    }
    updateState(state) {
        const managedIdentitiesSection = this.managedIdentitiesSection;
        if (!managedIdentitiesSection) {
            // A critical element is missing from the page, so fail early.
            this.policyEnabledLevels = ['Error'];
            return;
        }
        // Clear managed identities.
        while (managedIdentitiesSection.firstChild) {
            managedIdentitiesSection.removeChild(managedIdentitiesSection.firstChild);
        }
        if (!state) {
            this.policyEnabledLevels = ['Error'];
            return;
        }
        this.policyEnabledLevels = state.policyEnabledLevels;
        if (state.managedProfileIdentity) {
            managedIdentitiesSection.appendChild(this.createManagedIdentityElement('Profile', state.managedProfileIdentity));
        }
        if (state.managedBrowserIdentity) {
            managedIdentitiesSection.appendChild(this.createManagedIdentityElement('Browser', state.managedBrowserIdentity));
        }
    }
    setValueToElement(elementId, stringValue) {
        const htmlElement = this.$(elementId);
        if (htmlElement) {
            htmlElement.innerText = stringValue;
        }
        else {
            console.error(`Could not find ${elementId} element.`);
        }
    }
    createManagedIdentityElement(prefix, managedIdentity) {
        const identityElement = document.createElement('div');
        let keyValuePairs = [{ key: `${prefix} Identity Name`, value: managedIdentity.identityName }];
        if (managedIdentity.loadedKeyInfo) {
            keyValuePairs = keyValuePairs.concat([
                {
                    key: 'Key Trust Level',
                    value: utils.trustLevelToString(managedIdentity.loadedKeyInfo.trustLevel),
                },
                {
                    key: 'Key Type',
                    value: utils.keyTypeToString(managedIdentity.loadedKeyInfo.keyType),
                },
                {
                    key: 'Public Key Hash',
                    value: managedIdentity.loadedKeyInfo.encodedSpkiHash,
                },
                {
                    key: 'Has SSL Key',
                    value: managedIdentity.loadedKeyInfo.hasSslKey.toString(),
                },
            ]);
            if (managedIdentity.loadedKeyInfo.keyUploadStatus) {
                if (managedIdentity.loadedKeyInfo.keyUploadStatus.uploadClientError) {
                    keyValuePairs.push({
                        key: 'Key Upload Client Error',
                        value: managedIdentity.loadedKeyInfo.keyUploadStatus.uploadClientError,
                    });
                }
                else {
                    keyValuePairs.push({
                        key: 'Key Upload Response',
                        value: utils.keySyncCodeToString(managedIdentity.loadedKeyInfo.keyUploadStatus
                            .syncKeyResponseCode),
                    });
                }
            }
        }
        if (managedIdentity.certificateMetadata) {
            keyValuePairs = keyValuePairs.concat([
                {
                    key: 'Subject',
                    value: managedIdentity.certificateMetadata.subjectDisplayName,
                },
                {
                    key: 'Issuer',
                    value: managedIdentity.certificateMetadata.issuerDisplayName,
                },
                {
                    key: 'Serial Number',
                    value: managedIdentity.certificateMetadata.serialNumber,
                },
                {
                    key: 'SHA-256 Fingerprint',
                    value: managedIdentity.certificateMetadata.fingerprint,
                },
                {
                    key: 'Creation Date',
                    value: managedIdentity.certificateMetadata.creationDateString,
                },
                {
                    key: 'Expiration Date',
                    value: managedIdentity.certificateMetadata.expirationDateString,
                },
            ]);
        }
        for (const pair of keyValuePairs) {
            identityElement.appendChild(this.createLabelledValueElement(pair.key, pair.value));
        }
        return identityElement;
    }
    createLabelledValueElement(label, text) {
        const nameSpan = document.createElement('span');
        nameSpan.classList.add('bold');
        nameSpan.textContent = text;
        const containerElement = document.createElement('div');
        containerElement.appendChild(document.createTextNode(`${label}: `));
        containerElement.appendChild(nameSpan);
        return containerElement;
    }
}
customElements.define(ManagedClientCertificateElement.is, ManagedClientCertificateElement);
