from datetime import datetime
from pathlib import Path
import platform
import shutil
import os

from dotfile_manager.config import BIN_PATH, SOURCE_FILE_PATH
from dotfile_manager.project import Project


def get_os_name() -> str:
    platform_name = platform.system()
    # TODO(lgulich): Find way to also determine linux distro.
    if platform_name == 'Linux':
        return 'ubuntu'
    if platform_name == 'Darwin':
        return 'macos'
    raise


class Repo:

    def __init__(self, path: Path) -> None:
        self.path: Path = path

    def get_path(self) -> Path:
        return self.path

    def install_all(self, os_name: str = get_os_name()) -> None:
        for project_path in sorted(self.path.iterdir()):
            self.install(os.path.basename(project_path), os_name)
        print('Successfully installed all projects.')

    def install(self, project_name: str, os_name: str = get_os_name()) -> None:
            project = Project(self.path / project_name)
            if not project.is_valid_project():
                return
            if project.is_disabled():
                print(f'Project {project.get_name()} is disabled - Skipping.')
                return
            project.install(os_name)

    def setup_all(self) -> None:
        # Create folder into which all binaries will be symlinked.
        bin_path = self.path / BIN_PATH
        shutil.rmtree(bin_path, ignore_errors=True)
        bin_path.mkdir(parents=True)

        # Create file which contains everything that should be sourced.
        source_file_path = self.path / SOURCE_FILE_PATH
        source_file_path.unlink(missing_ok=True)
        source_file_path.parent.mkdir(parents=True, exist_ok=True)
        with open(source_file_path, 'a') as output_file:
            output_file.write(f'# Autogenerated on {datetime.now()}.\n')
            output_file.write('# shellcheck shell=sh\n\n')

            # Setup every project individually:
            for project_path in sorted(self.path.iterdir()):
                project = Project(project_path)
                if not project.is_valid_project():
                    continue
                if project.is_disabled():
                    print(f'Project {project.get_name()} is disabled - Skipping.')
                    continue
                print(f'Setting up {project.get_name()}:')
                project.create_symbolic_links()
                project.create_bin(bin_path)
                project.add_sources(output_file)

        print(f'Successfully setup all projects. Sourcing script created at "{source_file_path}". '
              f'Binaries located at "{bin_path}".')
