/*
Copyright 2019-2026 The Tekton Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
    http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/* istanbul ignore file */

import { Component } from 'react';
import { PrefixContext, SkeletonText } from '@carbon/react';
import { FixedSizeList as List } from 'react-window';
import { injectIntl, useIntl } from 'react-intl';
import { getStepStatusReason, isRunning } from '@tektoncd/dashboard-utils';
import { Information } from '@carbon/react/icons';

import DotSpinner from '../DotSpinner';
import LogFormat from '../LogFormat';

const itemSize = 16; // This should be kept in sync with the line-height in SCSS
const defaultHeight = itemSize * 100 + itemSize / 2;

export const logFormatRegex =
  /^((?<timestamp>\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2})?(.\d{3,9})?(Z|[+-]\d{2}:\d{2}))\s?)?(::(?<command>group|endgroup|error|warning|info|notice|debug|trace)::)?(?<message>.*)?$/s;

function LogsFilteredNotification({ displayedLogLines, totalLogLines }) {
  const intl = useIntl();

  if (displayedLogLines === totalLogLines) {
    return null;
  }

  if (displayedLogLines === 0) {
    return (
      <span className="tkn--log-filtered">
        <Information />
        {intl.formatMessage({
          id: 'dashboard.logs.hidden.all',
          defaultMessage:
            'All lines hidden due to selected log levels or collapsed groups'
        })}
      </span>
    );
  }

  const hiddenLines = totalLogLines - displayedLogLines;
  const message =
    hiddenLines === 1
      ? intl.formatMessage({
          id: 'dashboard.logs.hidden.one',
          defaultMessage:
            '1 line hidden due to selected log levels or collapsed groups'
        })
      : intl.formatMessage(
          {
            id: 'dashboard.logs.hidden',
            defaultMessage:
              '{numHiddenLines, plural, other {# lines}} hidden due to selected log levels or collapsed groups' // eslint-disable-line formatjs/enforce-plural-rules
          },
          { numHiddenLines: totalLogLines - displayedLogLines }
        );

  return (
    <span className="tkn--log-filtered">
      <Information />
      {message}
    </span>
  );
}

export class LogContainer extends Component {
  constructor(props) {
    super(props);
    this.state = { groupsExpanded: {}, loading: true, logs: [] };
  }

  componentDidMount() {
    this.loadLog();
  }

  componentWillUnmount() {
    clearTimeout(this.timer);
    this.cancelled = true;
  }

  onToggleGroup = ({ expanded, groupIndex }) => {
    this.setState(({ groupsExpanded }) => ({
      groupsExpanded: {
        ...groupsExpanded,
        [groupIndex]: expanded
      }
    }));
  };

  wasRunningAfterMounting = () => {
    if (this.alreadyWasRunningAfterMounting) {
      return true;
    }
    const { reason, status } = getStepStatusReason(this.props.stepStatus);
    if (isRunning(reason, status)) {
      // alreadyWasRunningAfterMounting is a class variable instead of state variable because a change in its value does not require a subsequent re-rendering
      this.alreadyWasRunningAfterMounting = true;
      return true;
    }
    return false;
  };

  getLogList = () => {
    const { intl } = this.props;
    const truncatedLineWarning = intl.formatMessage({
      id: 'dashboard.logs.lineTruncated',
      defaultMessage:
        'This log line has been truncated. To view the full content, download the raw logs.'
    });

    const {
      logLevels,
      maxLineLength,
      parseLogLine = line => {
        if (!line?.length) {
          return { message: line };
        }

        let truncatedLine = line;
        if (line.length > maxLineLength) {
          // Truncate extraordinarily long log lines to prevent performance
          // issues in the browser. We have encountered some users outputting
          // >2MB on a single log line which crashes even VS Code.
          truncatedLine =
            line.substring(0, maxLineLength) + ' … ' + truncatedLineWarning;
        }

        const {
          groups: { command, message, timestamp }
        } = logFormatRegex.exec(truncatedLine);
        let level;
        if (!['group', 'endgroup'].includes(command)) {
          level = command;
        }
        return {
          command,
          level,
          message,
          timestamp
        };
      },
      showLevels,
      showTimestamps,
      stepStatus
    } = this.props;
    const { reason } = (stepStatus && stepStatus.terminated) || {};
    const {
      groupsExpanded,
      logs = [
        intl.formatMessage({
          id: 'dashboard.pipelineRun.logEmpty',
          defaultMessage: 'No log available'
        })
      ]
    } = this.state;

    let previousTimestamp;
    let currentGroupIndex = null;
    let countEndGroupCommands = 0;
    const parsedLogs = logs.reduce((acc, line, index) => {
      const parsedLogLine = parseLogLine(line);
      if (!parsedLogLine.timestamp) {
        // multiline log, use same timestamp as previous line
        parsedLogLine.timestamp = previousTimestamp;
      } else {
        previousTimestamp = parsedLogLine.timestamp;
      }

      const isGroup = parsedLogLine.command === 'group';
      const isEndGroup = parsedLogLine.command === 'endgroup';
      if (isGroup) {
        currentGroupIndex = index;
        parsedLogLine.groupIndex = index;
        if (groupsExpanded[index] !== false) {
          // if not already explicitly collapsed,
          // respect state if explicitly expanded, otherwise
          // should be expanded by default if viewed when step running
          // or collapsed by default if viewing after run complete
          parsedLogLine.expanded =
            groupsExpanded[index] || this.wasRunningAfterMounting();
        }
      } else if (isEndGroup) {
        currentGroupIndex = null;
        countEndGroupCommands++;
        // we don't render anything for the endgroup command
        return acc;
      }

      if (!isGroup && currentGroupIndex !== null) {
        // we're inside a group, determine if the line should be rendered
        if (
          groupsExpanded[currentGroupIndex] === false ||
          (!groupsExpanded[currentGroupIndex] &&
            !this.wasRunningAfterMounting())
        ) {
          // skip if either explicitly collapsed, or viewed after step completed so collapsed by default
          return acc;
        }

        parsedLogLine.groupIndex = currentGroupIndex;
      }

      if (
        !logLevels ||
        // we treat lines with no log level as if they specified 'info'
        // but we don't display a default level for these lines to avoid
        // unnecessary noise for users not using the expected log format
        (!parsedLogLine.level && logLevels.info) ||
        logLevels[parsedLogLine.level]
      ) {
        acc.push(parsedLogLine);
      }
      return acc;
    }, []);

    // need to include endgroup commands in count of displayed log lines
    // otherwise we end up with wrong message about hidden lines displayed to
    // user even when all groups are expanded
    const displayedLogLines = parsedLogs.length + countEndGroupCommands;
    if (parsedLogs.length < 20_000) {
      return (
        <>
          <LogsFilteredNotification
            displayedLogLines={displayedLogLines}
            totalLogLines={logs.length}
          />
          <LogFormat
            fields={{ level: showLevels, timestamp: showTimestamps }}
            logs={parsedLogs}
            onToggleGroup={this.onToggleGroup}
          />
        </>
      );
    }

    const height = reason
      ? Math.min(defaultHeight, itemSize * logs.length)
      : defaultHeight;

    return (
      <>
        <LogsFilteredNotification
          displayedLogLines={displayedLogLines}
          totalLogLines={logs.length}
        />
        <List
          height={height}
          itemCount={parsedLogs.length}
          itemData={parsedLogs}
          itemSize={itemSize}
          width="100%"
        >
          {({ data, index, style }) => (
            <div style={style}>
              <LogFormat
                fields={{ level: showLevels, timestamp: showTimestamps }}
                logs={[data[index]]}
                onToggleGroup={this.onToggleGroup}
              />
            </div>
          )}
        </List>
      </>
    );
  };

  getTrailerMessage = ({ exitCode, reason, terminationReason }) => {
    const { forcePolling, intl, isSidecar } = this.props;

    if (isSidecar) {
      return null;
    }

    if (terminationReason === 'Skipped') {
      return intl.formatMessage({
        id: 'dashboard.pipelineRun.stepSkipped',
        defaultMessage: 'Step skipped'
      });
    }

    if (reason && forcePolling) {
      return (
        <>
          {intl.formatMessage({
            id: 'dashboard.logs.pending',
            defaultMessage: 'Final logs pending'
          })}
          <DotSpinner />
        </>
      );
    }

    switch (reason) {
      case 'Completed':
        if (exitCode !== 0) {
          return intl.formatMessage(
            {
              id: 'dashboard.pipelineRun.stepCompleted.exitCode',
              defaultMessage: 'Step completed with exit code {exitCode}'
            },
            { exitCode }
          );
        }
        return intl.formatMessage({
          id: 'dashboard.pipelineRun.stepCompleted',
          defaultMessage: 'Step completed successfully'
        });
      case 'Error':
        return intl.formatMessage({
          id: 'dashboard.pipelineRun.stepFailed',
          defaultMessage: 'Step failed'
        });
      default:
        return null;
    }
  };

  readChunks = ({ done, value }, decoder, text = '') => {
    if (this.cancelled) {
      this.reader.cancel();
      return undefined;
    }
    let logs = text;
    if (value) {
      logs += decoder.decode(value, { stream: !done });
      this.setState({
        loading: false,
        logs: logs.split(/\r?\n/)
      });
    } else {
      this.setState({
        loading: false
      });
    }
    if (done) {
      return undefined;
    }
    return this.reader
      .read()
      .then(result => this.readChunks(result, decoder, logs))
      .catch(error => {
        console.error(error);
        return this.loadLog();
      });
  };

  loadLog = async () => {
    // In development mode this request is duplicated due to usage of StrictMode component wrapper
    // It highlights a potential problem but only affects local dev and not production mode
    this.cancelled = false;

    const { fetchLogs, forcePolling, intl, stepStatus, pollingInterval } =
      this.props;
    if (!fetchLogs) {
      return;
    }

    let continuePolling = false;
    try {
      continuePolling = forcePolling || (stepStatus && !stepStatus.terminated);
      const logs = await fetchLogs();
      if (logs?.getReader) {
        // logs is a https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream
        const decoder = new TextDecoder();
        this.reader = logs.getReader();
        await this.reader
          .read()
          .then(result => this.readChunks(result, decoder))
          .catch(error => {
            throw error;
          });
      } else {
        this.setState({
          loading: false,
          logs: logs ? logs.split(/\r?\n/) : undefined
        });
        if (continuePolling) {
          clearTimeout(this.timer);
          this.timer = setTimeout(this.loadLog, pollingInterval);
        }
      }
    } catch (error) {
      console.error(error);
      this.setState({
        loading: false,
        logs: [
          intl.formatMessage({
            id: 'dashboard.pipelineRun.logFailed',
            defaultMessage: 'Unable to fetch log'
          })
        ]
      });
      if (continuePolling) {
        clearTimeout(this.timer);
        this.timer = setTimeout(this.loadLog, pollingInterval);
      }
    }
  };

  logTrailer = () => {
    const { forcePolling, stepStatus } = this.props;
    const { exitCode, reason } = (stepStatus && stepStatus.terminated) || {};
    const trailer = this.getTrailerMessage({
      exitCode,
      reason,
      terminationReason: stepStatus?.terminationReason
    });
    if (!trailer) {
      return null;
    }

    return (
      <div
        className="tkn--log-trailer"
        data-status={reason && (forcePolling ? 'LogsPending' : reason)}
      >
        {trailer}
      </div>
    );
  };

  render() {
    const { toolbar } = this.props;
    const { loading } = this.state;
    return (
      <pre className="tkn--log tkn--theme-dark">
        {loading ? (
          <SkeletonText paragraph width="60%" />
        ) : (
          <>
            {toolbar}
            <div className="tkn--log-container">{this.getLogList()}</div>
            {this.logTrailer()}
          </>
        )}
      </pre>
    );
  }
}
LogContainer.contextType = PrefixContext;
LogContainer.defaultProps = {
  maxLineLength: 64 * 1024,
  pollingInterval: 4000
};

export default injectIntl(LogContainer);
