import brkt_cli
import logging
import os

import googleapiclient

from brkt_cli.subcommand import Subcommand

from brkt_cli import encryptor_service, instance_config_args, util
from brkt_cli.instance_config import (
    INSTANCE_CREATOR_MODE,
    INSTANCE_METAVISOR_MODE,
    INSTANCE_UPDATER_MODE,
)
from brkt_cli.instance_config_args import (
    instance_config_from_values,
    setup_instance_config_args
)
from brkt_cli.gcp import (
    encrypt_gcp_image,
    encrypt_gcp_image_args,
    gcp_service,
    launch_gcp_image,
    launch_gcp_image_args,
    update_gcp_image,
    update_encrypted_gcp_image_args,
    wrap_gcp_image,
    wrap_gcp_image_args,
    share_logs_gcp_args,
)
from brkt_cli.validation import ValidationError

log = logging.getLogger(__name__)


def run_encrypt(values, config):
    session_id = util.make_nonce()
    gcp_svc = gcp_service.GCPService(values.project, session_id, log)
    check_args(values, gcp_svc, config)

    encrypted_image_name = gcp_service.get_image_name(
        values.encrypted_image_name, values.image)
    gcp_service.validate_image_name(encrypted_image_name)
    if values.validate:
        gcp_service.validate_images(gcp_svc,
                                    encrypted_image_name,
                                    values.encryptor_image,
                                    values.image,
                                    values.image_project)
        if values.gcp_tags:
            validate_tags(values.gcp_tags)

    if not values.verbose:
        logging.getLogger('googleapiclient').setLevel(logging.ERROR)

    if not values.encryptor_image:
        # create metavisor image from file in GCS bucket
        log.info('Retrieving encryptor image from GCS bucket')
        try:
            values.encryptor_image = gcp_svc.get_latest_encryptor_image(
                values.zone, values.bucket, image_file=values.image_file)
        except googleapiclient.errors.HttpError:
            log.exception('GCP API call to create image from file failed')
            return 1
    else:
        # Keep user provided encryptor image
        values.keep_encryptor = True

    log.info('Starting encryptor session %s', gcp_svc.get_session_id())

    brkt_env = brkt_cli.brkt_env_from_values(values, config)
    lt = instance_config_args.get_launch_token(values, config)
    ic = instance_config_from_values(
        values,
        mode=INSTANCE_CREATOR_MODE,
        brkt_env=brkt_env,
        launch_token=lt
    )

    encrypted_image_id = encrypt_gcp_image.encrypt(
        gcp_svc=gcp_svc,
        enc_svc_cls=encryptor_service.EncryptorService,
        values=values,
        encrypted_image_name=encrypted_image_name,