
const { WebTracerProvider } = require('@opentelemetry/sdk-trace-web');
// import { WebTracerProvider } from '@opentelemetry/sdk-trace-web'
const { Resource } = require('@opentelemetry/resources');
const { SemanticResourceAttributes } = require('@opentelemetry/semantic-conventions');
const { getWebAutoInstrumentations } = require('@opentelemetry/auto-instrumentations-web');
const { ConsoleSpanExporter, SimpleSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { registerInstrumentations } = require('@opentelemetry/instrumentation');
const { ZoneContextManager } = require('@opentelemetry/context-zone');
const { context, propagation, trace } = require('@opentelemetry/api');
const { TRACE_PARENT_HEADER, W3CTraceContextPropagator } = require('@opentelemetry/core');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');

const ds = document.currentScript.dataset;
if (ds.mode == 'dev') {
    console.log(ds, ds.appAlias);
}

const serviceName = ds.serviceName || 'observe-front';
const serviceVersion = ds.serviceVersion || '0.1.0';
const commandLine = '-DAPP_NAME=' + (ds.appAlias || 'OBSERVE');    // 暂时为兼容otel-collector的修改
// const otelTraceExporter = ds.exporterOtlpTraceEndpoint;

// const otelTraceExporter='http://otel-collector.cestong.com.cn/v1/traces';  //本公司使用

// const otelTraceExporter='http://21.47.83.250:32639';  //甲方使用

const otelTraceExporter='/col/v1/traces';  //本公司使用

const resource = Resource.default().merge(
    new Resource({
        [SemanticResourceAttributes.SERVICE_NAME]: serviceName,
        [SemanticResourceAttributes.SERVICE_VERSION]: serviceVersion,
        [SemanticResourceAttributes.PROCESS_COMMAND_LINE]: commandLine
    })
);

const provider = new WebTracerProvider({
    resource: resource,
});
if (ds.mode == 'dev') {
    provider.addSpanProcessor(new SimpleSpanProcessor(new ConsoleSpanExporter()));
}
provider.addSpanProcessor(new SimpleSpanProcessor(
    new OTLPTraceExporter({
        url: otelTraceExporter,
    })

));
provider.register({
    contextManager: new ZoneContextManager(),
    propagator: new W3CTraceContextPropagator(),
});


const instrumentations = getWebAutoInstrumentations({
    '@opentelemetry/instrumentation-xml-http-request': {
        clearTimingResources: true,
        propagateTraceHeaderCorsUrls: [ // 只有能匹配到的对外请求，才会在请求时添加Traceparent请求头
            /.+/g,
        ],
    },
    '@opentelemetry/instrumentation-fetch': {
        propagateTraceHeaderCorsUrls: [
            /.+/g,
        ],
    },
});
registerInstrumentations({
    instrumentations,
    tracerProvider: provider,
});

var defaultContext;

const metaElement = Array.from(document.getElementsByTagName('meta')).find(
    e => e.getAttribute('name') === TRACE_PARENT_HEADER
);
const traceparent = (metaElement && metaElement.content) || '';
if (traceparent == '') {
    const tracer = trace.getTracer(
        'front-tracer'
    );
    tracer.startActiveSpan('Document Load', (span) => {
        defaultContext = context.active();
        span.end();
    })
} else {
    defaultContext = propagation.extract(context.active(), { traceparent });
}

// export function OneTrace (fn) {
//     context.with(defaultContext, async () => {
//         fn()
//     })
// }
