#!/usr/bin/env python3
import tts
import argparse
import os.path
import sys
import codecs
import locale
import _io
import json
import zipfile
import logging

class TTS_CLI:
  def __init__(self):
    self.preferences=tts.preferences.Preferences()

    parser = argparse.ArgumentParser(description="Manipulate Tabletop Simulator files")
    parser.add_argument("-d","--directory",help="Override TTS cache directory")
    parser.add_argument("-l","--loglevel",help="Set logging level",choices=['debug','info','warn','error'])
    subparsers = parser.add_subparsers(dest='parser',title='command',description='Valid commands.')
    subparsers.required=True

  # add list command
    parser_list = subparsers.add_parser('list',help="List installed mods.",description='''
    List installed mods.
    If no id is provided, then this will return a list of all installed modules.
    If an id is provided, then this will list the contents of that modules.
    ''')
    group_list=parser_list.add_mutually_exclusive_group()
    group_list.add_argument("-w","--workshop",action="store_const",metavar='save_type',dest='save_type',const=tts.SaveType.workshop,help="List workshop files (the default).")
    group_list.add_argument("-s","--save",action="store_const",metavar='save_type',dest='save_type',const=tts.SaveType.save,help="List saves.")
    group_list.add_argument("-c","--chest",action="store_const",metavar='save_type',dest='save_type',const=tts.SaveType.chest,help="List chest files.")

    parser_list.add_argument("id",nargs='?',help="ID of specific mod to list details of.")
    parser_list.set_defaults(func=self.do_list)

    # export command
    parser_export = subparsers.add_parser('export',help="Export a mod.",description='Export a mod in a format suitible for later import.')
    group_export=parser_export.add_mutually_exclusive_group()
    group_export.add_argument("-w","--workshop",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.workshop,help="ID is of workshop file (the default).")
    group_export.add_argument("-s","--save",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.save,help="ID is of savegame file.")
    group_export.add_argument("-c","--chest",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.chest,help="ID is of chest file.")
    parser_export.add_argument("id",help="ID of mod/name of savegame to export.")
    parser_export.add_argument("-o","--output",help="Location/file to export to.")
    parser_export.add_argument("-f","--force",action="store_true",help="Force creation of export file.")
    parser_export.add_argument("-d","--download",action="store_true",help="Attempt to download missing cache files. (EXPERIMENTAL)")
    parser_export.set_defaults(func=self.do_export)

    # import command
    parser_import = subparsers.add_parser('import',help="Import a mod.",description="Import an previously exported mod.")
    parser_import.add_argument("file",help="Mod pak file to import.")
    parser_import.set_defaults(func=self.do_import)

    # download command
    parser_download = subparsers.add_parser('download',help='Download mod files.',description='Attempt to download any missing files for an installed mod.')
    group_download=parser_download.add_mutually_exclusive_group()
    group_download.add_argument("-w","--workshop",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.workshop,help="ID is of workshop file.")
    group_download.add_argument("-s","--save",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.save,help="ID is of savegame file.")
    group_download.add_argument("-c","--chest",action="store_const",dest='save_type',metavar='save_type',const=tts.SaveType.chest,help="ID is of chest file.")
    group_download_target=parser_download.add_mutually_exclusive_group(required=True)
    group_download_target.add_argument("-a","--all",action="store_true",help="Download all.")
    group_download_target.add_argument("id",nargs='?',help="ID of mod/name of savegame to download.")
    parser_download.set_defaults(func=self.do_download)

    # cache command
    parser_cache = subparsers.add_parser('cache',help='Work with the cache.')
    subparsers_cache = parser_cache.add_subparsers(dest='parser_cache',title='cache_command',description='Valid sub-commands.')
    subparsers_cache.required = True
    parser_cache_create = subparsers_cache.add_parser('create',help='(re)create cache directory')
    parser_cache_create.set_defaults(func=self.do_cache_create)

    # config command
    parser_config = subparsers.add_parser('config',help='Configure tts manager.')
    subparsers_config = parser_config.add_subparsers(dest='parser_config',title='config_command',description='Valid sub-commands.')
    subparsers_config.required = True
    parser_config_list = subparsers_config.add_parser('list',help='List configuration.')
    parser_config_list.set_defaults(func=self.do_config_list)
    parser_config_validate = subparsers_config.add_parser('validate',help='Validate configuration.')
    parser_config_validate.set_defaults(func=self.do_config_validate)
    parser_config_reset = subparsers_config.add_parser('reset',help='Reset configuration.')
    parser_config_reset.set_defaults(func=self.do_config_reset)
    parser_config_set = subparsers_config.add_parser('set',help='Set configuration parameters.')
    parser_config_set.set_defaults(func=self.do_config_set)
    parser_config_set.add_argument("-m","--mod_location",choices=['documents','gamedata'],help="Where mods are stored.")
    parser_config_set.add_argument("-t","--tts_location",help="TTS Install directory")

    args = parser.parse_args()

    # set logging
    if args.loglevel:
      logmap={
        'debug':logging.DEBUG,
        'info':logging.INFO,
        'warn':logging.WARN,
        'error':logging.ERROR
       }
      tts.logger().setLevel(logmap[args.loglevel])
    else:
      tts.logger().setLevel(logging.WARN)

    # load filesystem values
    if args.directory:
      self.filesystem = tts.filesystem.FileSystem(os.path.abspath(args.directory))