#!/usr/bin/env python3

import argparse
import sketchfab as sf
import logging

from sketchfab.models import SFModel


logging.basicConfig(format='%(asctime)-15s %(message)s', level=logging.DEBUG)

parser = argparse.ArgumentParser(description=f'Sketchfab v{sf.VERSION}')
subparsers = parser.add_subparsers(dest='command', required=True, help='Command to use')

# Collections listing
parser_list_collections = subparsers.add_parser('list_collections')

# Models listing
parser_list_models = subparsers.add_parser('list_models')

# Model update
parser_model_update = subparsers.add_parser('update_model')
parser_model_update.add_argument('-u', '--uid', required=True, help='Model UID to update')

# Upload
parser_model_upload = subparsers.add_parser('upload')
parser_model_upload.add_argument('-f', '--file', required=True, help='File to upload')

# Shared between upload and update
for p in parser_model_update, parser_model_upload:
    p.add_argument('-n', '--name', help='Name to set for the model')
    p.add_argument('-d', '--description', help='Description of the model')
    p.add_argument('-t', '--tags', help='Tags to set', nargs='+')
    p.add_argument('-p', '--public', choices=('true', 'false'), help='Publicly accessible')
    p.add_argument('-os', '--opt-shading', choices=('shadeless', 'lit'), help='Switch to shadeless')


args = parser.parse_args()

sfc = sf.Client()


def parse_model_args(a: argparse.Namespace, model: SFModel):
    if a.opt_shading:
        model.options.shading = 'shadeless'

    if a.name:
        model.name = args.name

    if a.description:
        model.description = args.description

    if a.tags:
        model.tags = args.tags

    if a.public is not None:
        model.private = a.public == 'true'


def app_list_collections():
    print("Collections:")
    for c in sfc.collections():
        print(f"- {c.name} ({c.uid})")


def app_list_models():
    print("Models:")
    for m in sfc.models():
        print(f"- {m.name} ({m.uid})")


def app_upload():
    logging.info("Uploading...")
    model = SFModel()
    if args.public is not None:
        args.public = False
    parse_model_args(args, model)
    model = sfc.upload_model(args.file, model)
    if model:
        logging.info("Done ! uid = %s", model.uid)
    else:
        logging.warning("Failed !")


def app_model_update():
    model = sfc.get_model(args.uid)
    if not model:
        print("Couldn't fetch the model", args.uid)
        return
    parse_model_args(args, model)
    if model.update():
        print("Update successful !")
    else:
        print("Update failed !")


if args.command == 'list_collections':
    app_list_collections()
elif args.command == 'list_models':
    app_list_models()
elif args.command == 'upload':
    app_upload()
elif args.command == 'update_model':
    app_model_update()
