"use strict";

/*
Copyright (c) 2018-2019 Uber Technologies, Inc.

This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
*/

/* global module */
function getStyledImportName(j, root) {
  var baseImports = root.find(j.ImportDeclaration, {
    source: {
      value: 'baseui'
    }
  });

  if (baseImports.length) {
    var styledImports = baseImports.find(j.ImportSpecifier, {
      imported: {
        name: 'styled'
      }
    });

    if (styledImports.length) {
      return styledImports.get(0).node.local.name;
    }
  }

  return null;
}

function containsFlowComment(j, root) {
  var getBodyNode = function getBodyNode() {
    return root.find(j.Program).get('body', 0).node;
  };

  var comments = getBodyNode().comments || [];
  return comments.filter(function (e) {
    return e.value.indexOf('@flow') !== -1;
  }).length > 0;
}

module.exports = function (file, api, options) {
  var j = api.jscodeshift;
  var root = j(file.source);

  if (containsFlowComment(j, root)) {
    var styledImportName = getStyledImportName(j, root);

    if (styledImportName) {
      var comment = j.commentLine(' $FlowFixMe', true, false);
      var styledComponents = root.find(j.VariableDeclaration).filter(function (path) {
        var calls = j(path).find(j.CallExpression, {
          callee: {
            name: styledImportName
          }
        });
        return Boolean(calls.length);
      });
      styledComponents.forEach(function (path) {
        path.node.comments = path.node.comments || [];
        path.node.comments.push(comment);
      });
    }
  }

  return root.toSource();
};

module.exports.parser = 'flow';