from invoke import task
import time
import git
import pathlib
import os
import subprocess
from . utils import internal_api
from . utils import message
from . utils import aws
import contextlib
import requests
import platform


def a():
    # define global variable
    repo = git.Repo('.', search_parent_directories=True)
    NOW = time.strftime("%Y%m%d_%H%m%S")
    ROOT = GIT_ROOT = pathlib.PurePath(repo.working_tree_dir).as_posix()

    GIT_SHA = repo.head.object.hexsha

    BUILD_ROOT_DIR = f"{ROOT}/__DB"

    DATA_ROOT_DIR = ''
    TEMPLATE_DIR = f"{ROOT}/tools/tool_data/AutoGenerated.DB/template"
    OUTPUT_CS_DIR = f"{ROOT}/tools/tool_data/AutoGenerated.DB/output"
    GEN_DLL_FPATH = f"{ROOT}/tools/tool_data/AutoGenerated.DB/bin/Debug/net46/AutoGenerated.DB.dll"
    GEN_DB_FPATH = f"{BUILD_ROOT_DIR}/client.db"
    PASSWORD = ""


    LOCALE_ROOT_DIR = ''
    LOCALE_TEMPLATE_DIR = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/template"
    LOCALE_CS_DIR = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/output"
    LOCALE_DLL_FPATH = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/bin/Debug/net46/AutoGenerated.LOCALE.dll"
    LOCALE_DB_FPATH = f"{BUILD_ROOT_DIR}/locale.db"
    LOCALE_PASSWORD = ""

    # ensure directory.
    pathlib.Path(BUILD_ROOT_DIR).mkdir(parents=True, exist_ok=True)



def dotnet_run(args):
    cmd = f"dotnet run {args}"
    if platform.system() == 'Darwin':
        cmd = f"dotnet mono -f net46 -mo=\"--arch=32 --debug\" --loggerlevel Verbose -po=\"{args}\""
    print(cmd)
    return cmd



@contextlib.contextmanager
def chdir(dirname=None):
    #ref : https://github.com/pyinvoke/invoke/issues/225
    curdir = os.getcwd()
    try:
        if dirname is not None:
            os.chdir(dirname)
        yield
    finally:
        os.chdir(curdir)

@task()
def db_update(ctx):
    """generate db && upload aws"""

    fpath = db_generate(ctx)
    db_validate(ctx)

    api = internal_api.DBUpdater()
    curr_ver, err = api.get_version()
    if err :
        message(err)
        exit(-1)

    next_ver = curr_ver + 1
    data, err = aws.upload_db_to_aws(fpath, next_ver)
    if err :
        message(err)
        exit(-1)

    ok, err = api.update_version(next_ver, data['hash'])
    if err :
        message(err)
        exit(-1)

    message(f"[success] db_update : {curr_ver} => {next_ver}")



@task()
def locale_update(ctx, country):
    """generate locale && upload aws"""

    fpath = locale_generate(ctx, country)

    api = internal_api.LocaleUpdater()
    curr_ver, err = api.get_version()
    if err :
        message(err)
        exit(-1)

    next_ver = curr_ver + 1
    data, err = aws.upload_locale_to_aws(fpath, next_ver)
    if err :
        message(err)
        exit(-1)

    ok, err = api.update_version(next_ver, data['hash'])
    if err :
        message(err)
        exit(-1)

    message(f"[success] locale_update - {country} : {curr_ver} => {next_ver}")


@task()
def db_validate(ctx):
    """validate client db"""

    with chdir('tools/tool_data'):

        with chdir('ETC.ValidateDB'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i {GEN_DB_FPATH}"))


@task()
def db_generate(ctx):
    """generate client db"""
    with chdir('tools/tool_locale'):
        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {LOCALE_CS_DIR}"))


    with chdir('tools/tool_data'):
        with chdir('SQLite.Attribute'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.ClassGenerator'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-e {DATA_ROOT_DIR} -t {TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))

        with chdir('AutoGenerated.DB'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.DataExporter'):
            ctx.run(f"dotnet restore")
            ctx.run(dotnet_run(f"-d {GEN_DLL_FPATH} -e {DATA_ROOT_DIR} -o {GEN_DB_FPATH}"))
    return GEN_DB_FPATH

@task()
def autogen_db(ctx):
    """generate autogen.cs for unity_project"""

    # generate db cs
    OUTPUT_CS_DIR = ''
    pathlib.Path(OUTPUT_CS_DIR).mkdir(parents=True, exist_ok=True)

    with chdir('tools/tool_data'):
        with chdir('NF.CLI.ClassGenerator'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-e {DATA_ROOT_DIR} -t {TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))

    # generate locale cs
    OUTPUT_CS_DIR = ''
    pathlib.Path(OUTPUT_CS_DIR).mkdir(parents=True, exist_ok=True)
    with chdir('tools/tool_locale'):
        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))
    print("done")

@task()
def locale_generate(ctx, country):
    """generate locale db"""

    with chdir('tools/tool_locale'):
        with chdir('SQLite.Attribute'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {LOCALE_CS_DIR}"))

        with chdir('AutoGenerated.LOCALE'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.DataExporter.LOCALE'):
            ctx.run(f"dotnet restore")
            ctx.run(dotnet_run(f"-i {country} -d {LOCALE_DLL_FPATH} -e {LOCALE_ROOT_DIR} -o {LOCALE_DB_FPATH}"))
    return LOCALE_DB_FPATH

from invoke import task
import time
import git
import pathlib
import os
import subprocess
from . utils import internal_api
from . utils import message
from . utils import aws
import contextlib
import requests
import platform


def a():
    # define global variable
    repo = git.Repo('.', search_parent_directories=True)
    NOW = time.strftime("%Y%m%d_%H%m%S")
    ROOT = GIT_ROOT = pathlib.PurePath(repo.working_tree_dir).as_posix()

    GIT_SHA = repo.head.object.hexsha

    BUILD_ROOT_DIR = f"{ROOT}/__DB"

    DATA_ROOT_DIR = ''
    TEMPLATE_DIR = f"{ROOT}/tools/tool_data/AutoGenerated.DB/template"
    OUTPUT_CS_DIR = f"{ROOT}/tools/tool_data/AutoGenerated.DB/output"
    GEN_DLL_FPATH = f"{ROOT}/tools/tool_data/AutoGenerated.DB/bin/Debug/net46/AutoGenerated.DB.dll"
    GEN_DB_FPATH = f"{BUILD_ROOT_DIR}/client.db"
    PASSWORD = ""


    LOCALE_ROOT_DIR = ''
    LOCALE_TEMPLATE_DIR = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/template"
    LOCALE_CS_DIR = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/output"
    LOCALE_DLL_FPATH = f"{ROOT}/tools/tool_locale/AutoGenerated.LOCALE/bin/Debug/net46/AutoGenerated.LOCALE.dll"
    LOCALE_DB_FPATH = f"{BUILD_ROOT_DIR}/locale.db"
    LOCALE_PASSWORD = ""

    # ensure directory.
    pathlib.Path(BUILD_ROOT_DIR).mkdir(parents=True, exist_ok=True)



def dotnet_run(args):
    cmd = f"dotnet run {args}"
    if platform.system() == 'Darwin':
        cmd = f"dotnet mono -f net46 -mo=\"--arch=32 --debug\" --loggerlevel Verbose -po=\"{args}\""
    print(cmd)
    return cmd



@contextlib.contextmanager
def chdir(dirname=None):
    #ref : https://github.com/pyinvoke/invoke/issues/225
    curdir = os.getcwd()
    try:
        if dirname is not None:
            os.chdir(dirname)
        yield
    finally:
        os.chdir(curdir)

@task()
def db_update(ctx):
    """generate db && upload aws"""

    fpath = db_generate(ctx)
    db_validate(ctx)

    api = internal_api.DBUpdater()
    curr_ver, err = api.get_version()
    if err :
        message(err)
        exit(-1)

    next_ver = curr_ver + 1
    data, err = aws.upload_db_to_aws(fpath, next_ver)
    if err :
        message(err)
        exit(-1)

    ok, err = api.update_version(next_ver, data['hash'])
    if err :
        message(err)
        exit(-1)

    message(f"[success] db_update : {curr_ver} => {next_ver}")



@task()
def locale_update(ctx, country):
    """generate locale && upload aws"""

    fpath = locale_generate(ctx, country)

    api = internal_api.LocaleUpdater()
    curr_ver, err = api.get_version()
    if err :
        message(err)
        exit(-1)

    next_ver = curr_ver + 1
    data, err = aws.upload_locale_to_aws(fpath, next_ver)
    if err :
        message(err)
        exit(-1)

    ok, err = api.update_version(next_ver, data['hash'])
    if err :
        message(err)
        exit(-1)

    message(f"[success] locale_update - {country} : {curr_ver} => {next_ver}")


@task()
def db_validate(ctx):
    """validate client db"""

    with chdir('tools/tool_data'):

        with chdir('ETC.ValidateDB'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i {GEN_DB_FPATH}"))


@task()
def db_generate(ctx):
    """generate client db"""
    with chdir('tools/tool_locale'):
        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {LOCALE_CS_DIR}"))


    with chdir('tools/tool_data'):
        with chdir('SQLite.Attribute'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.ClassGenerator'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-e {DATA_ROOT_DIR} -t {TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))

        with chdir('AutoGenerated.DB'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.DataExporter'):
            ctx.run(f"dotnet restore")
            ctx.run(dotnet_run(f"-d {GEN_DLL_FPATH} -e {DATA_ROOT_DIR} -o {GEN_DB_FPATH}"))
    return GEN_DB_FPATH

@task()
def autogen_db(ctx):
    """generate autogen.cs for unity_project"""

    # generate db cs
    OUTPUT_CS_DIR = ''
    pathlib.Path(OUTPUT_CS_DIR).mkdir(parents=True, exist_ok=True)

    with chdir('tools/tool_data'):
        with chdir('NF.CLI.ClassGenerator'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-e {DATA_ROOT_DIR} -t {TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))

    # generate locale cs
    OUTPUT_CS_DIR = ''
    pathlib.Path(OUTPUT_CS_DIR).mkdir(parents=True, exist_ok=True)
    with chdir('tools/tool_locale'):
        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {OUTPUT_CS_DIR}"))
    print("done")

@task()
def locale_generate(ctx, country):
    """generate locale db"""

    with chdir('tools/tool_locale'):
        with chdir('SQLite.Attribute'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.ClassGenerator.LOCALE'):
            ctx.run("dotnet restore")
            ctx.run(dotnet_run(f"-i ENG -e {LOCALE_ROOT_DIR} -t {LOCALE_TEMPLATE_DIR} -o {LOCALE_CS_DIR}"))

        with chdir('AutoGenerated.LOCALE'):
            ctx.run('dotnet restore')
            ctx.run("dotnet build")

        with chdir('NF.CLI.DataExporter.LOCALE'):
            ctx.run(f"dotnet restore")
            ctx.run(dotnet_run(f"-i {country} -d {LOCALE_DLL_FPATH} -e {LOCALE_ROOT_DIR} -o {LOCALE_DB_FPATH}"))
    return LOCALE_DB_FPATH

# define global variable # ensure directory. #ref : https://github.com/pyinvoke/invoke/issues/225 generate db && upload aws generate locale && upload aws validate client db generate client db generate autogen.cs for unity_project # generate db cs # generate locale cs generate locale db