# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# 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.

# pylint: disable=line-too-long,too-many-arguments,too-many-locals


import json
import os

import click

from platformio import fs
from platformio.package.commands.install import install_project_dependencies
from platformio.package.manager.platform import PlatformPackageManager
from platformio.platform.exception import UnknownBoard
from platformio.project.config import ProjectConfig
from platformio.project.generator import ProjectGenerator
from platformio.project.helpers import is_platformio_project


def validate_boards(ctx, param, value):  # pylint: disable=W0613
    pm = PlatformPackageManager()
    for id_ in value:
        try:
            pm.board_config(id_)
        except UnknownBoard:
            raise click.BadParameter(
                "`%s`. Please search for board ID using `platformio boards` "
                "command" % id_
            )
    return value


@click.command("init", short_help="Initialize a project or update existing")
@click.option(
    "--project-dir",
    "-d",
    default=os.getcwd,
    type=click.Path(
        exists=True, file_okay=False, dir_okay=True, writable=True, resolve_path=True
    ),
)
@click.option("-b", "--board", multiple=True, metavar="ID", callback=validate_boards)
@click.option("--ide", type=click.Choice(ProjectGenerator.get_supported_ides()))
@click.option("-e", "--environment", help="Update existing environment")
@click.option("-O", "--project-option", multiple=True)
@click.option("--env-prefix", default="")
@click.option("--no-install-dependencies", is_flag=True)
@click.option("-s", "--silent", is_flag=True)
def project_init_cmd(
    project_dir,
    board,
    ide,
    environment,
    project_option,
    env_prefix,
    no_install_dependencies,
    silent,
):
    is_new_project = not is_platformio_project(project_dir)
    if is_new_project:
        if not silent:
            print_header(project_dir)
        init_base_project(project_dir)

    if environment:
        update_project_env(project_dir, environment, project_option)
    elif board:
        update_board_envs(project_dir, board, project_option, env_prefix)

    # resolve project dependencies
    if not no_install_dependencies and (environment or board):
        install_project_dependencies(
            options=dict(
                project_dir=project_dir,
                environments=[environment] if environment else [],
                silent=silent,
            )
        )

    if ide:
        if not silent:
            click.echo(
                "Updating metadata for the %s IDE..." % click.style(ide, fg="cyan")
            )
        with fs.cd(project_dir):
            config = ProjectConfig.get_instance(
                os.path.join(project_dir, "platformio.ini")
            )
            config.validate()
            ProjectGenerator(config, environment, ide, board).generate()

    if is_new_project:
        init_cvs_ignore(project_dir)

    if not silent:
        print_footer(is_new_project)


def print_header(project_dir):
    if project_dir == os.getcwd():
        click.secho("\nThe current working directory ", fg="yellow", nl=False)
        try:
            click.secho(project_dir, fg="cyan", nl=False)
        except UnicodeEncodeError:
            click.secho(json.dumps(project_dir), fg="cyan", nl=False)
        click.secho(" will be used for the project.", fg="yellow")
        click.echo("")

    click.echo("The next files/directories have been created in ", nl=False)
    try:
        click.secho(project_dir, fg="cyan")
    except UnicodeEncodeError:
        click.secho(json.dumps(project_dir), fg="cyan")
    click.echo("%s - Put project header files here" % click.style("include", fg="cyan"))
    click.echo(
        "%s - Put here project specific (private) libraries"
        % click.style("lib", fg="cyan")
    )
    click.echo("%s - Put project source files here" % click.style("src", fg="cyan"))
    click.echo(
        "%s - Project Configuration File" % click.style("platformio.ini", fg="cyan")
    )


def print_footer(is_new_project):
    if is_new_project:
        return click.secho(
            "\nProject has been successfully initialized! Useful commands:\n"
            "`pio run` - process/build project from the current directory\n"
            "`pio run --target upload` or `pio run -t upload` "
            "- upload firmware to a target\n"
            "`pio run --target clean` - clean project (remove compiled files)"
            "\n`pio run --help` - additional information",
            fg="green",
        )
    return click.secho(
        "Project has been successfully updated!",
        fg="green",
    )


def init_base_project(project_dir):
    with fs.cd(project_dir):
        config = ProjectConfig()
        config.save()
        dir_to_readme = [
            (config.get("platformio", "src_dir"), None),
            (config.get("platformio", "include_dir"), init_include_readme),
            (config.get("platformio", "lib_dir"), init_lib_readme),
            (config.get("platformio", "test_dir"), init_test_readme),
        ]
        for (path, cb) in dir_to_readme:
            if os.path.isdir(path):
                continue
            os.makedirs(path)
            if cb:
                cb(path)


def init_include_readme(include_dir):
    with open(os.path.join(include_dir, "README"), mode="w", encoding="utf8") as fp:
        fp.write(
            """
This directory is intended for project header files.

A header file is a file containing C declarations and macro definitions
to be shared between several project source files. You request the use of a
header file in your project source file (C, C++, etc) located in `src` folder
by including it, with the C preprocessing directive `#include'.

```src/main.c

#include "header.h"

int main (void)
{
 ...
}
```

Including a header file produces the same results as copying the header file
into each source file that needs it. Such copying would be time-consuming
and error-prone. With a header file, the related declarations appear
in only one place. If they need to be changed, they can be changed in one
place, and programs that include the header file will automatically use the
new version when next recompiled. The header file eliminates the labor of
finding and changing all the copies as well as the risk that a failure to
find one copy will result in inconsistencies within a program.

In C, the usual convention is to give header files names that end with `.h'.
It is most portable to use only letters, digits, dashes, and underscores in
header file names, and at most one dot.

Read more about using header files in official GCC documentation:

* Include Syntax
* Include Operation
* Once-Only Headers
* Computed Includes

https://gcc.gnu.org/onlinedocs/cpp/Header-Files.html
""",
        )


def init_lib_readme(lib_dir):
    with open(os.path.join(lib_dir, "README"), mode="w", encoding="utf8") as fp:
        fp.write(
            """
This directory is intended for project specific (private) libraries.
PlatformIO will compile them to static libraries and link into executable file.

The source code of each library should be placed in a an own separate directory
("lib/your_library_name/[here are source files]").

For example, see a structure of the following two libraries `Foo` and `Bar`:

|--lib
|  |
|  |--Bar
|  |  |--docs
|  |  |--examples
|  |  |--src
|  |     |- Bar.c
|  |     |- Bar.h
|  |  |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html
|  |
|  |--Foo
|  |  |- Foo.c
|  |  |- Foo.h
|  |
|  |- README --> THIS FILE
|
|- platformio.ini
|--src
   |- main.c

and a contents of `src/main.c`:
```
#include <Foo.h>
#include <Bar.h>

int main (void)
{
  ...
}

```

PlatformIO Library Dependency Finder will find automatically dependent
libraries scanning project source files.

More information about PlatformIO Library Dependency Finder
- https://docs.platformio.org/page/librarymanager/ldf.html
""",
        )


def init_test_readme(test_dir):
    with open(os.path.join(test_dir, "README"), mode="w", encoding="utf8") as fp:
        fp.write(
            """
This directory is intended for PlatformIO Test Runner and project tests.

Unit Testing is a software testing method by which individual units of
source code, sets of one or more MCU program modules together with associated
control data, usage procedures, and operating procedures, are tested to
determine whether they are fit for use. Unit testing finds problems early
in the development cycle.

More information about PlatformIO Unit Testing:
- https://docs.platformio.org/en/latest/advanced/unit-testing/index.html
""",
        )


def init_cvs_ignore(project_dir):
    conf_path = os.path.join(project_dir, ".gitignore")
    if os.path.isfile(conf_path):
        return
    with open(conf_path, mode="w", encoding="utf8") as fp:
        fp.write(".pio\n")


def update_board_envs(project_dir, board_ids, project_option, env_prefix):
    config = ProjectConfig(
        os.path.join(project_dir, "platformio.ini"), parse_extra=False
    )
    used_boards = []
    for section in config.sections():
        cond = [section.startswith("env:"), config.has_option(section, "board")]
        if all(cond):
            used_boards.append(config.get(section, "board"))

    pm = PlatformPackageManager()
    modified = False
    for id_ in board_ids:
        board_config = pm.board_config(id_)
        if id_ in used_boards:
            continue
        used_boards.append(id_)
        modified = True

        envopts = {"platform": board_config["platform"], "board": id_}
        # find default framework for board
        frameworks = board_config.get("frameworks")
        if frameworks:
            envopts["framework"] = frameworks[0]

        for item in project_option:
            if "=" not in item:
                continue
            _name, _value = item.split("=", 1)
            envopts[_name.strip()] = _value.strip()

        section = "env:%s%s" % (env_prefix, id_)
        config.add_section(section)

        for option, value in envopts.items():
            config.set(section, option, value)

    if modified:
        config.save()


def update_project_env(project_dir, environment, project_option):
    if not project_option:
        return
    config = ProjectConfig(
        os.path.join(project_dir, "platformio.ini"), parse_extra=False
    )

    section = "env:%s" % environment
    if not config.has_section(section):
        config.add_section(section)

    for item in project_option:
        if "=" not in item:
            continue
        _name, _value = item.split("=", 1)
        config.set(section, _name.strip(), _value.strip())

    config.save()

[((45, 1, 45, 76), 'click.command', 'click.command', (), '', False, 'import click\n'), ((54, 1, 54, 85), 'click.option', 'click.option', (), '', False, 'import click\n'), ((56, 1, 56, 72), 'click.option', 'click.option', (), '', False, 'import click\n'), ((57, 1, 57, 54), 'click.option', 'click.option', (), '', False, 'import click\n'), ((58, 1, 58, 41), 'click.option', 'click.option', (), '', False, 'import click\n'), ((59, 1, 59, 56), 'click.option', 'click.option', (), '', False, 'import click\n'), ((60, 1, 60, 45), 'click.option', 'click.option', (), '', False, 'import click\n'), ((33, 9, 33, 33), 'platformio.package.manager.platform.PlatformPackageManager', 'PlatformPackageManager', ({}, {}), '()', False, 'from platformio.package.manager.platform import PlatformPackageManager\n'), ((121, 4, 121, 76), 'click.echo', 'click.echo', (), '', False, 'import click\n'), ((148, 11, 151, 5), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((290, 16, 290, 55), 'os.path.join', 'os.path.join', ({(290, 29, 290, 40): 'project_dir', (290, 42, 290, 54): '""".gitignore"""'}, {}), "(project_dir, '.gitignore')", False, 'import os\n'), ((291, 7, 291, 32), 'os.path.isfile', 'os.path.isfile', ({(291, 22, 291, 31): 'conf_path'}, {}), '(conf_path)', False, 'import os\n'), ((307, 9, 307, 33), 'platformio.package.manager.platform.PlatformPackageManager', 'PlatformPackageManager', ({}, {}), '()', False, 'from platformio.package.manager.platform import PlatformPackageManager\n'), ((71, 25, 71, 59), 'platformio.project.helpers.is_platformio_project', 'is_platformio_project', ({(71, 47, 71, 58): 'project_dir'}, {}), '(project_dir)', False, 'from platformio.project.helpers import is_platformio_project\n'), ((50, 9, 52, 5), 'click.Path', 'click.Path', (), '', False, 'import click\n'), ((112, 22, 112, 33), 'os.getcwd', 'os.getcwd', ({}, {}), '()', False, 'import os\n'), ((113, 8, 113, 78), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((118, 8, 118, 66), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((119, 8, 119, 22), 'click.echo', 'click.echo', ({(119, 19, 119, 21): '""""""'}, {}), "('')", False, 'import click\n'), ((123, 8, 123, 43), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((139, 15, 147, 9), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((155, 9, 155, 27), 'platformio.fs.cd', 'fs.cd', ({(155, 15, 155, 26): 'project_dir'}, {}), '(project_dir)', False, 'from platformio import fs\n'), ((156, 17, 156, 32), 'platformio.project.config.ProjectConfig', 'ProjectConfig', ({}, {}), '()', False, 'from platformio.project.config import ProjectConfig\n'), ((299, 8, 299, 51), 'os.path.join', 'os.path.join', ({(299, 21, 299, 32): 'project_dir', (299, 34, 299, 50): '"""platformio.ini"""'}, {}), "(project_dir, 'platformio.ini')", False, 'import os\n'), ((342, 8, 342, 51), 'os.path.join', 'os.path.join', ({(342, 21, 342, 32): 'project_dir', (342, 34, 342, 50): '"""platformio.ini"""'}, {}), "(project_dir, 'platformio.ini')", False, 'import os\n'), ((97, 13, 97, 31), 'platformio.fs.cd', 'fs.cd', ({(97, 19, 97, 30): 'project_dir'}, {}), '(project_dir)', False, 'from platformio import fs\n'), ((55, 41, 55, 78), 'platformio.project.generator.ProjectGenerator.get_supported_ides', 'ProjectGenerator.get_supported_ides', ({}, {}), '()', False, 'from platformio.project.generator import ProjectGenerator\n'), ((115, 12, 115, 57), 'click.secho', 'click.secho', (), '', False, 'import click\n'), ((126, 54, 126, 87), 'click.style', 'click.style', (), '', False, 'import click\n'), ((129, 10, 129, 39), 'click.style', 'click.style', (), '', False, 'import click\n'), ((131, 54, 131, 83), 'click.style', 'click.style', (), '', False, 'import click\n'), ((133, 44, 133, 84), 'click.style', 'click.style', (), '', False, 'import click\n'), ((165, 15, 165, 34), 'os.path.isdir', 'os.path.isdir', ({(165, 29, 165, 33): 'path'}, {}), '(path)', False, 'import os\n'), ((167, 12, 167, 29), 'os.makedirs', 'os.makedirs', ({(167, 24, 167, 28): 'path'}, {}), '(path)', False, 'import os\n'), ((173, 14, 173, 49), 'os.path.join', 'os.path.join', ({(173, 27, 173, 38): 'include_dir', (173, 40, 173, 48): '"""README"""'}, {}), "(include_dir, 'README')", False, 'import os\n'), ((219, 14, 219, 45), 'os.path.join', 'os.path.join', ({(219, 27, 219, 34): 'lib_dir', (219, 36, 219, 44): '"""README"""'}, {}), "(lib_dir, 'README')", False, 'import os\n'), ((272, 14, 272, 46), 'os.path.join', 'os.path.join', ({(272, 27, 272, 35): 'test_dir', (272, 37, 272, 45): '"""README"""'}, {}), "(test_dir, 'README')", False, 'import os\n'), ((38, 18, 41, 13), 'click.BadParameter', 'click.BadParameter', ({(39, 16, 40, 31): "('`%s`. Please search for board ID using `platformio boards` command' % id_)"}, {}), "(\n    '`%s`. Please search for board ID using `platformio boards` command' % id_)", False, 'import click\n'), ((99, 16, 99, 59), 'os.path.join', 'os.path.join', ({(99, 29, 99, 40): 'project_dir', (99, 42, 99, 58): '"""platformio.ini"""'}, {}), "(project_dir, 'platformio.ini')", False, 'import os\n'), ((125, 20, 125, 43), 'json.dumps', 'json.dumps', ({(125, 31, 125, 42): 'project_dir'}, {}), '(project_dir)', False, 'import json\n'), ((95, 56, 95, 83), 'click.style', 'click.style', (), '', False, 'import click\n'), ((102, 12, 102, 61), 'platformio.project.generator.ProjectGenerator', 'ProjectGenerator', ({(102, 29, 102, 35): 'config', (102, 37, 102, 48): 'environment', (102, 50, 102, 53): 'ide', (102, 55, 102, 60): 'board'}, {}), '(config, environment, ide, board)', False, 'from platformio.project.generator import ProjectGenerator\n'), ((117, 24, 117, 47), 'json.dumps', 'json.dumps', ({(117, 35, 117, 46): 'project_dir'}, {}), '(project_dir)', False, 'import json\n')]