#!/usr/bin/env python
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Generates an Android Studio project from a GN target."""

import argparse
import codecs
import logging
import os
import shutil
import subprocess
import sys
import zipfile

_BUILD_ANDROID = os.path.join(os.path.dirname(__file__), os.pardir)
sys.path.append(_BUILD_ANDROID)
import devil_chromium
from devil.utils import run_tests_helper
from pylib import constants
from pylib.constants import host_paths

sys.path.append(os.path.join(_BUILD_ANDROID, 'gyp'))
import jinja_template
from util import build_utils


_DEFAULT_ANDROID_MANIFEST_PATH = os.path.join(
    host_paths.DIR_SOURCE_ROOT, 'build', 'android', 'AndroidManifest.xml')
_JINJA_TEMPLATE_PATH = os.path.join(
    os.path.dirname(__file__), 'build.gradle.jinja')

_JAVA_SUBDIR = 'symlinked-java'
_SRCJARS_SUBDIR = 'extracted-srcjars'


def _RebasePath(path_or_list, new_cwd=None, old_cwd=None):
  """Makes the given path(s) relative to new_cwd, or absolute if not specified.

  If new_cwd is not specified, absolute paths are returned.
  If old_cwd is not specified, constants.GetOutDirectory() is assumed.
  """
  if not isinstance(path_or_list, basestring):
    return [_RebasePath(p, new_cwd, old_cwd) for p in path_or_list]
  if old_cwd is None:
    old_cwd = constants.GetOutDirectory()
  old_cwd = os.path.abspath(old_cwd)
  if new_cwd:
    new_cwd = os.path.abspath(new_cwd)
    return os.path.relpath(os.path.join(old_cwd, path_or_list), new_cwd)
  return os.path.abspath(os.path.join(old_cwd, path_or_list))


def _IsSubpathOf(child, parent):
  """Returns whether |child| is a subpath of |parent|."""
  return not os.path.relpath(child, parent).startswith(os.pardir)


def _WriteFile(path, data):
  """Writes |data| to |path|, constucting parent directories if necessary."""
  logging.info('Writing %s', path)
  dirname = os.path.dirname(path)
  if not os.path.exists(dirname):
    os.makedirs(dirname)
  with codecs.open(path, 'w', 'utf-8') as output_file:
    output_file.write(data)


def _RunNinja(output_dir, ninja_targets):
  cmd = ['ninja', '-C', output_dir, '-j50']
  cmd.extend(ninja_targets)
  logging.info('Running: %r', cmd)
  subprocess.check_call(cmd)


class _ProjectEntry(object):
  """Helper class for various path transformations."""
  def __init__(self, gn_target):
    assert gn_target.startswith('//'), gn_target
    if ':' not in gn_target:
      gn_target = '%s:%s' % (gn_target, os.path.basename(gn_target))
    self._gn_target = gn_target
    self._build_config = None

  @classmethod
  def FromBuildConfigPath(cls, path):
    prefix = 'gen/'
    suffix = '.build_config'
    assert path.startswith(prefix) and path.endswith(suffix), path
    subdir = path[len(prefix):-len(suffix)]
    return cls('//%s:%s' % (os.path.split(subdir)))

  def __hash__(self):
    return hash(self._gn_target)

  def __eq__(self, other):
    return self._gn_target == other.GnTarget()

  def GnTarget(self):
    return self._gn_target

  def NinjaTarget(self):
    return self._gn_target[2:]

  def GnBuildConfigTarget(self):
    return '%s__build_config' % self._gn_target

  def NinjaBuildConfigTarget(self):
    return '%s__build_config' % self.NinjaTarget()

  def GradleSubdir(self):
    """Returns the output subdirectory."""
    return self.NinjaTarget().replace(':', os.path.sep)

  def ProjectName(self):
    """Returns the Gradle project name."""
    return self.GradleSubdir().replace(os.path.sep, '\\$')

  def BuildConfig(self):
    """Reads and returns the project's .build_config JSON."""
    if not self._build_config:
      path = os.path.join('gen', self.GradleSubdir() + '.build_config')
      self._build_config = build_utils.ReadJson(_RebasePath(path))
    return self._build_config


def _ComputeJavaSourceDirs(java_files):
  """Returns the list of source directories for the given files."""
  found_roots = set()
  for path in java_files:
    path_root = path
    # Recognize these tokens as top-level.
    while os.path.basename(path_root) not in ('javax', 'org', 'com', 'src'):
      assert path_root, 'Failed to find source dir for ' + path
      path_root = os.path.dirname(path_root)
    # Assume that if we've hit "src", the we're at the root.
    if os.path.basename(path_root) != 'src':
      path_root = os.path.dirname(path_root)
    found_roots.add(path_root)
  return list(found_roots)


def _CreateSymlinkTree(entry_output_dir, symlink_dir, desired_files,
                       parent_dirs):
  """Creates a directory tree of symlinks to the given files.

  The idea here is to replicate a directory tree while leaving out files within
  it not listed by |desired_files|.
  """
  assert _IsSubpathOf(symlink_dir, entry_output_dir)
  if os.path.exists(symlink_dir):
    shutil.rmtree(symlink_dir)

  for target_path in desired_files:
    prefix = next(d for d in parent_dirs if target_path.startswith(d))
    subpath = os.path.relpath(target_path, prefix)
    symlinked_path = os.path.join(symlink_dir, subpath)
    symlinked_dir = os.path.dirname(symlinked_path)
    if not os.path.exists(symlinked_dir):
      os.makedirs(symlinked_dir)
    relpath = os.path.relpath(target_path, symlinked_dir)
    logging.debug('Creating symlink %s -> %s', symlinked_path, relpath)
    os.symlink(relpath, symlinked_path)


def _CreateJavaSourceDir(entry_output_dir, java_sources_file):
  """Computes and constructs when necessary the list of java source directories.

  1. Computes the root java source directories from the list of files.
  2. Determines whether there are any .java files in them that are not included
     in |java_sources_file|.
  3. If not, returns the list of java source directories. If so, constructs a
     tree of symlinks within |entry_output_dir| of all files in
     |java_sources_file|.
  """