#!/usr/bin/env node
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * @format
 */

'use strict';

const SignedSource = require('signedsource');
const fs = require('fs');
const glob = require('glob');
const path = require('path');
const reactDocs = require('react-docgen');

const GENERATE_ANNOTATION = '@' + 'generate-docs';
const RN_ROOT = path.join(__dirname, '..');
const OUTPUT_PATH = path.join(RN_ROOT, 'docs', 'generatedComponentApiDocs.js');

const TEMPLATE = `/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 *
 * This file is used by the React Native website to show the props of core components
 * This file was generated by running scripts/generate-api-docs.js
 *
 * ::_SIGNING_TOKEN_::
 */

'use strict';

module.exports = ::_CONTENT_::
`;

const allComponentFiles = glob.sync(
  path.join(RN_ROOT, '/Libraries/Components/**/*.js'),
  {
    nodir: true,
  },
);

const docs = allComponentFiles.reduce((acc, file) => {
  const contents = fs.readFileSync(file, {encoding: 'utf-8'});
  if (!contents.includes(GENERATE_ANNOTATION)) {
    return acc;
  }

  const result = reactDocs.parse(
    contents,
    reactDocs.resolver.findExportedComponentDefinition,
  );

  acc.push(cleanComponentResult(result));

  return acc;
}, []);

const content = TEMPLATE.replace(
  '::_CONTENT_::',
  JSON.stringify(docs, null, 2),
).replace('::_SIGNING_TOKEN_::', SignedSource.getSigningToken());

const signedContent = SignedSource.signFile(content);

if (process.env.NODE_ENV === 'test') {
  const existingContent = fs.readFileSync(OUTPUT_PATH, 'utf8');
  if (signedContent !== existingContent) {
    console.error(
      path.relative(RN_ROOT, OUTPUT_PATH),
      'is not up to date. Run',
      'scripts/generate-api-docs.js',
      'to regenerate the file.',
    );
    process.exit(1);
  }
} else {
  fs.writeFileSync(OUTPUT_PATH, SignedSource.signFile(content));
}

function cleanComponentResult(component) {
  return {
    ...component,
    methods: component.methods.filter(method => !method.name.startsWith('_')),
  };
}
