from pathlib import Path
from sys import stdout
from pkg_resources import resource_string
from .python_util import execute

class ResourceApi():
    def read_resource(self, path: str) -> bytes:
        return resource_string(__name__, path)

class FileApi():
    def clean_dir(self, directory: str):
        execute('rm -rf ' + directory, shell=True)
        execute('mkdir -p ' + directory, shell=True)

    def cp_force(self, src: str, target_dir: str):
        execute('cp -f ' + src + '* ' + target_dir, shell=True)

    def cp_recursive(self, src: str, target_dir: str):
        execute('cp -r ' + src + ' ' + target_dir, shell=True)

    def write_to_file(self, path: Path, data: bytes):
        with open(path, "w", encoding=stdout.encoding) as output_file:
            output_file.write(data.decode(stdout.encoding))

class DockerApi():
    def image(self, name: str, path: Path):
        execute('docker build -t ' + name +
            ' --file ' + path + '/image/Dockerfile '
            + path + '/image', shell=True)

    def drun(self, name: str):
        execute('docker run -it --entrypoint="" ' +
            name + ' /bin/bash', shell=True)

    def dockerhub_login(self, username: str, password: str):
        execute('docker login --username ' + username +
            ' --password ' + password, shell=True)

    def dockerhub_publish(self, name: str, username: str, tag=None):
        if tag is not None:
            execute('docker tag ' + name + ' ' + username +
            '/' + name + ':' + tag, shell=True)
            execute('docker push ' + username +
            '/' + name + ':' + tag, shell=True)
        execute('docker tag ' + name + ' ' + username +
            '/' + name + ':latest', shell=True)
        execute('docker push ' + username +
        '/' + name + ':latest', shell=True)

    def test(self, name: str, path: Path):
        execute('docker build -t ' + name + '-test ' +
            '--file ' + path + '/test/Dockerfile '
            + path + '/test', shell=True)