# -*- 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.

import sys
from os import path
from calculate.lib.datavars import (Variable, ReadonlyVariable, VariableError,
                                    TableVariable)
from calculate.core.server.api_types import LazyString
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 VariableClBackupFile(Variable):
    """
    Путь до создаваемое архива резервной копии
    """

    def get_backup(self):
        """
        Получить путь для подготовки архива настроек
        :return:
        """
        dn = self.Get('cl_backup_base_path')
        dt = datetime.datetime.now().strftime("%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(listDirectory(dn, fullPath=True), 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()
