# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import os

from . import Command
from ..config import Config
from ..machine import Machine, MachineCollection
from ..results import Results
from ..benchmarks import Benchmarks
from ..console import log
from .. import util
from .run import Run


class Update(Command):
    @classmethod
    def setup_arguments(cls, subparsers):
        parser = subparsers.add_parser(
            "update", help="Update the results and config files "
            "to the current version",
            description="Update the results and config files "
            "to the current version")

        parser.set_defaults(func=cls.run_from_args)

        return parser

    @classmethod
    def run_from_args(cls, args):
        return cls.run(args.config)

    @classmethod
    def run(cls, config_path):
        MachineCollection.update()
        Config.update(config_path)

        conf = Config.load(config_path)

        log.info("Updating results data...")

        for root, dirs, files in os.walk(conf.results_dir):
            for filename in files:
                path = os.path.join(root, filename)
                if filename == 'machine.json':
                    Machine.update(path)
                elif filename == "benchmarks.json":
                    pass
                elif filename.endswith('.json'):
                    Results.update(path)

        # Check benchmarks.json
        log.info("Updating benchmarks.json...")
        ok = False
        try:
            Benchmarks.load(conf)
            ok = True
        except util.UserError:
            pass

        if not ok:
            # Regenerating the file is needed
            with log.indent():
                Run.run(conf, bench=['just-discover'])

@@ -201,16 +201,26 @@
 mport os
+%0Aimport re
 %0A%0Afrom .
@@ -341,16 +341,30 @@
  Results
+, get_filename
 %0Afrom ..
@@ -1558,24 +1558,759 @@
 date(path)%0A%0A
+                    # Rename files if necessary%0A                    m = re.match(r'%5E(%5B0-9a-f%5D+)-(.*)%5C.json$', os.path.basename(path), re.I)%0A                    if m:%0A                        new_path = get_filename(root, m.group(1), m.group(2))%0A                        if new_path != path:%0A                            try:%0A                                if os.path.exists(new_path):%0A                                    raise OSError()%0A                                os.rename(path, new_path)%0A                            except OSError:%0A                                log.warn(%22%7B%7D: should be renamed to %7B%7D%22.format(path, new_path))%0A                    else:%0A                        log.warn(%22%7B%7D: unrecognized file name%22.format(path))%0A%0A
         # Ch

Rename misnamed results files in asv update