import json
import time
from scripts.utils.logger import logger
from scripts.utils.command import *


def write_build_log(os, build_info):
    """
    Module to write build logs.

    :param build_info:
    :param os:
    :return:
    """

    commands = None

    # getting build information
    if os == 'windows':
        commands = WindowsCommands(build_info['channel_config']['repository'],
                                   build_info['channel_config']['branch'],
                                   build_info['channel_config']['timestamp'])
    elif os == 'linux':
        commands = LinuxCommands(build_info['channel_config']['repository'],
                                 build_info['channel_config']['branch'],
                                 build_info['channel_config']['timestamp'])

    # writing build info
    file_write(f"{commands.build_path}.txt", build_info)
    file_write(f"{commands.build_path}/version.txt", {"version": build_info['channel_config']['branch'],
                                                      "Date": time.asctime()})


def file_write(path, data):
    """
    Module to write to file.

    :param path:
    :param data:
    :return:
    """

    try:
        with open(path, 'w+') as file:
            file.write(json.dumps(data))
            file.close()
    except Exception as es:
        logger.exception(f"Exception while writing {path} : {es}")
        return False

    return True
