__author__ = 'slaskawi@redhat.com'

import sys
import logging
import fileinput
import re
import os


class VersionUpdater:
    def __init__(self, configuration):
        self._configuration = configuration

    def update_version(self):
        target_full_version = self._configuration.get_full_release_version()
        target_version = self._configuration.get_release_version()
        productized_repo_location = self._configuration.get_productization_repo_location()
        packaging_repo_location = self._configuration.get_packaging_repo_location()

        self.replace_in_file(productized_repo_location + "/core/src/main/java/org/infinispan/Version.java",
                             "SNAPSHOT = \w+;$",
                             "SNAPSHOT = false;")
        self.replace_in_file(productized_repo_location + "/core/src/main/java/org/infinispan/Version.java",
                             "MAJOR = \"\d\";$",
                             "MAJOR = \"" + self._configuration.get_release_version_major() + "\";")
        self.replace_in_file(productized_repo_location + "/core/src/main/java/org/infinispan/Version.java",
                             "MINOR = \"\d\";$",
                             "MINOR = \"" + self._configuration.get_release_version_minor() + "\";")
        self.replace_in_file(productized_repo_location + "/core/src/main/java/org/infinispan/Version.java",
                             "MICRO = \"\d\";$",
                             "MICRO = \"" + self._configuration.get_release_version_micro() + "\";")
        self.replace_in_file(productized_repo_location + "/core/src/main/java/org/infinispan/Version.java",
                             "MODIFIER = \"\w+\";$",
                             "MODIFIER = \"" + self._configuration.get_release_version_modifier() + "\";")

        os.system(
            "./" + packaging_repo_location + "/bin/reversion.sh --new-revision " + target_full_version + " --pom-location " + productized_repo_location + "/pom.xml")

        self.replace_in_file(packaging_repo_location + "/pom.xml",
                             "<version.org.infinispan>.*</version.org.infinispan>",
                             "<version.org.infinispan>" + target_full_version + "</version.org.infinispan>")
        self.replace_in_file(packaging_repo_location + "/pom.xml",
                             r"<version>\d\.\d\.\d</version>",
                             "<version>" + target_version + "</version>")

    def replace_in_file(self, file, searchExp, replaceExp, count=1):
        for line in fileinput.input(file, inplace=1):
            if re.search(searchExp, line) and count > 0:
                logging.debug("Replacing: %s to: %s in file: %s", searchExp, replaceExp, file)
                line = re.sub(searchExp, replaceExp, line)
                count -= 1
            sys.stdout.write(line)