#!/opt/anaconda1anaconda2anaconda3/bin/python
# -*- coding: utf-8

import sys

import anvio
import datetime
import anvio.utils as utils
import anvio.terminal as terminal
import anvio.filesnpaths as filesnpaths

from anvio.errors import ConfigError, FilesNPathsError
from anvio.tables.states import TablesForStates


__author__ = "Developers of anvi'o (see AUTHORS.txt)"
__copyright__ = "Copyleft 2015-2018, the Meren Lab (http://merenlab.org/)"
__credits__ = []
__license__ = "GPL 3.0"
__version__ = anvio.__version__
__maintainer__ = "A. Murat Eren"
__email__ = "a.murat.eren@gmail.com"
__requires__ = ['pan-db', 'profile-db', 'state-json']
__provides__ = ['state']


run = terminal.Run()
progress = terminal.Progress()


def main(args):
    utils.is_pan_or_profile_db(args.pan_or_profile_db, genes_db_is_also_accepted=True)
    filesnpaths.is_file_json_formatted(args.state)
    utils.is_this_name_OK_for_database('--name parameter', args.name)

    states_table = TablesForStates(args.pan_or_profile_db)

    name = args.name
    content = open(args.state).read()
    last_modified = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")

    states_table.store_state(name, content, last_modified)

    run.info('Done', 'State "%s" is added to the database' % args.name)


if __name__ == '__main__':
    import argparse

    parser = argparse.ArgumentParser(description="Import an anvi'o state into a profile database.")

    parser.add_argument(*anvio.A('pan-or-profile-db'), **anvio.K('pan-or-profile-db'))
    parser.add_argument('-s', '--state', metavar="STATE_FILE", default = None, required = True,
                        help = "JSON serializable anvi'o state file.")
    parser.add_argument('-n', '--name', metavar = 'STATE_NAME', default = None, required = True,
                        help = 'State name.')

    args = anvio.get_args(parser)

    try:
        main(args)
    except ConfigError as e:
        print(e)
        sys.exit(-1)
    except FilesNPathsError as e:
        print(e)
        sys.exit(-2)
