# -*- coding: utf-8 -*-

# Copyright 2016 Mir Calculate. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0 #
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

from __future__ import absolute_import
import sys
from os import path
from calculate.lib.datavars import (Variable, ReadonlyVariable)
from calculate.lib.utils.files import get_free_dirname, listDirectory

from calculate.lib.cl_lang import setLocalTranslate
import datetime
from .action import Actions

_ = lambda x: x
setLocalTranslate('cl_core3', sys.modules[__name__])


class VariableClBackupPath(Variable):
    """
    Путь до каталога, где будет подготавливаться backup
    """
    preferred_dn = '/var/calculate/tmp/backup_prepare'

    def get(self):
        return get_free_dirname(self.preferred_dn)


class VariableClBackupContentsName(Variable):
    """
    Названия файла CONTENTS в архиве
    """
    value_format = "CONTENTS"


class VariableClBackupRootName(Variable):
    """
    Названия каталога, куда сохраняются конфигурационные файлы
    """
    value_format = "root"


class VariableClBackupFileContents(ReadonlyVariable):
    """
    CONTENTS в архиве настроек
    """
    value_format = "{cl_backup_path}/{cl_backup_contents_name}"


class VariableClBackupIniEnv(Variable):
    """
    Названия файла CONTENTS в архиве [install] init =
    """
    value_format = "{cl_backup_path}/ini.env"


class VariableClBackupBasePath(Variable):
    """
    Директория в которой будет создан архив
    """
    value = "/var/calculate/backup"


class VariableClBackupTime(ReadonlyVariable):
    """
    Переменная содержащая информацию: время создания backup
    """

    def init(self):
        self.label = _("Backup created")

    def get(self):
        backup_fn = self.Get('cl_backup_file')
        if backup_fn and path.exists(backup_fn):
            try:
                dt = datetime.datetime.strptime(
                    path.basename(backup_fn).rpartition("-")[2],
                    "%Y%m%d%H%M%S.tar.bz2")
                return dt.strftime("%s")
            except ValueError:
                pass
        return ""

    def humanReadable(self):
        ts = self.Get()
        if ts:
            ret = []
            backup_tm = datetime.datetime.fromtimestamp(int(ts))
            now_tm = datetime.datetime.now()
            backup_diff = now_tm - backup_tm
            if backup_diff.days:
                ret.append(_("%d days") % backup_diff.days)
            minute = 60
            hour = 60 * minute
            times = backup_diff.seconds
            if times >= hour:
                ret.append(_("%d hours") % (times / hour))
                times %= hour
            if times >= minute:
                ret.append(_("%d minutes") % (times / minute))
                times %= minute
            if times:
                ret.append(_("%d seconds") % times)
            return _("%s ago") % (" ".join(ret))

        return _("Unknown")


class VariableClBackupFile(Variable):
    """
    Путь до создаваемое архива резервной копии
    """

    def init(self):
        self.label = _("Backup file")

    def get_backup(self):
        """
        Получить путь для подготовки архива настроек
        :return:
        """
        dn = self.Get('cl_backup_base_path')
        dt = datetime.datetime.now().strftime(
            "calculate-backup-%Y%m%d%H%M%S.tar.bz2")
        return path.join(dn, dt)

    def get_restore(self):
        """
        Получить путь для распаковки архива настроек
        :return:
        """
        dn = self.Get('cl_backup_base_path')
        for fn in sorted((x for x in listDirectory(dn, fullPath=True)
                          if x.endswith(".tar.bz2")),
                         reverse=True):
            # получить самый свежий файл
            return fn
        return ""

    def get(self):
        action = self.Get('cl_action')
        if action == Actions.Backup:
            return self.get_backup()
        elif action == Actions.BackupRestore:
            return self.get_restore()

class VariableClBackupVerboseSet(Variable):
    """
    Verbose output for backup
    """
    type = "bool"
    opt = ["-v", "--verbose"]
    value = "off"

    def init(self):
        self.help = _("verbose output")
        self.label = _("Verbose output")
