import json
import os
from configparser import ConfigParser, ExtendedInterpolation

from django.conf import settings

from sandbox.libs.cmd_process import CmdProcessInteractive
from sandbox.libs.context.models import SandboxContext
from sandbox.libs.logger import logger_by_name

# predicate for actions which depend on provision package
provision_generated_predicate = (lambda: SandboxContext.is_provision_generated(),
                                 'provision package should be generated before')


def increment_version(version: str):
    """
    Simple increment of TrustList/Firmware version
    """
    major, minor, *_ = version.split('.')
    major, minor = int(major), int(minor)
    if minor < 255:
        minor += 1
    else:
        major += 1
        minor = 0

    return f'{major}.{minor}.1.1'


def get_tp_process():
    """
    Prepare Trust Provisioner process, without launch
    """
    logger = logger_by_name('virgil-trust-provisioner')
    cmd = ('virgil-trust-provisioner '
           '-c {0} '
           '-t {1} '
           '-i {2} '
           '-y').format(_create_tp_config(),
                        settings.VIRGIL_APP_TOKEN,
                        _create_factory_info_json())
    process = CmdProcessInteractive(cmd, logger=logger)
    return process


def _create_tp_config():
    path = os.path.join(settings.SANDBOX_TEMP_DIR, 'provisioner.conf')
    if os.path.exists(path):
        return path
    parser = ConfigParser(interpolation=ExtendedInterpolation())
    parser['MAIN'] = {
        'storage_path': settings.SANDBOX_TP_DIR,
        'log_path': settings.SANDBOX_TP_DIR,
        'provision_pack_path': settings.SANDBOX_PROVISION_PACK_DIR
    }
    parser['VIRGIL'] = {
        'iot_api_url': settings.API_GATEWAY_URL,
    }
    with open(path, 'w') as configfile:
        parser.write(configfile)
    return path


def _create_factory_info_json():
    path = os.path.join(settings.SANDBOX_TEMP_DIR, 'factory_info_sample.json')
    if os.path.exists(path):
        return path
    data = {
        'name': 'Sample Factory Name',
        'address': 'sample address',
        'contacts': 'sample_factory@some_mail.com'
    }

    with open(path, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=4)
    return path
