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

import sys
import argparse

import anvio.db as db
import anvio.dbops as dbops
import anvio.terminal as terminal 

from anvio.errors import ConfigError


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

current_version = '4'
next_version    = '5'


def update_pan_db(pan_db_path, just_do_it = False):
    if pan_db_path is None:
        raise ConfigError("No database path is given.")

    # make sure someone is not being funny
    dbops.is_pan_db(pan_db_path)

    # make sure the version is accurate
    pan_db = db.DB(pan_db_path, None, ignore_version = True)
    if str(pan_db.get_version()) != current_version:
        raise ConfigError("Version of this pan database is not %s (hence, this script cannot really do anything)." % current_version)

    if not just_do_it:
        try:
            run.warning("This script will upgrade your pan database from v%s to v%s. This upgrade will simply add a new field into\
                         your single or merged pan database to store a 'description' about the data represented in it. So you have\
                         a field to store information to remember later on, or make sure others have access to some information about\
                         the database when you are working with it. You can just press ENTER to continue.\
                         If you want to cancel the upgrade and think more about it, press CTRL+C now. If you want to avoid\
                         this message the next time, use '--just-do-it'." % (current_version, next_version))
            input("Press ENTER to continue...\n")
        except:
            print()
            sys.exit()

    progress.new("Trying to upgrade the pan database")
    progress.update('...')

    pan_db.set_meta_value('description', '_No description is found_')

    # set the version
    pan_db.remove_meta_key_value_pair('version')
    pan_db.set_version(next_version)

    # bye
    pan_db.disconnect()
    progress.end()


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='A simple script to upgrade pan database from version %s to version %s' % (current_version, next_version))
    parser.add_argument('pan_db', metavar = 'PAN_DB', help = "An anvi'o pan database of version %s" % current_version)
    parser.add_argument('--just-do-it', default=False, action="store_true", help = "Do not bother me with warnings")
    args = parser.parse_args()

    try:
        update_pan_db(args.pan_db, just_do_it = args.just_do_it)
    except ConfigError as e:
        print(e)
        sys.exit(-1)
