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

# Copyright 2015-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.install import distr
from calculate.lib.utils.git import Git
from calculate.lib.utils.files import pathJoin
from calculate.lib.datavars import (ReadonlyVariable, FieldValue)
from calculate.lib.variables import linux as lib_linux
from calculate.lib.variables import system as lib_system
from calculate.update.variables import update
from calculate.update import profile as update_profile

from calculate.lib.cl_lang import setLocalTranslate
from calculate.update.variables.update import DataVarsUpdateProfile
from calculate.builder.variables.action import Actions

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


class VariableClBuilderGit(ReadonlyVariable):
    type = "object"

    def get(self):
        chroot_path = self.Get('builder.cl_builder_path')
        sshkey = pathJoin(chroot_path,
                          self.Get('update.cl_update_sshkey_path'))
        if path.exists(sshkey):
            return Git(sshkey)
        else:
            return Git()

class VariableClBuilderProfileStorage(ReadonlyVariable):
    type = "object"

    def get(self):
        git = self.Get('cl_builder_git')
        builder_path = self.Get('cl_builder_path')
        if builder_path:
            builder_ls = path.join(builder_path, "var/lib/layman")
            return update_profile.RepositoryStorageSet(
                update_profile.LocalStorage(git, builder_ls),
                update_profile.CacheStorage(git, '/var/calculate/tmp/update'))
        else:
            return update_profile.RepositoryStorageSet(
                update_profile.CacheStorage(git, '/var/calculate/tmp/update'))



class VariableClBuilderProfileUrl(update.VariableClUpdateProfileUrl):
    """
    URL репозитория
    """
    check_after = ["cl_builder_profile_branch"]

    profile = "builder.cl_builder_profile_system"
    branch = "builder.cl_builder_profile_branch"
    storage = "builder.cl_builder_profile_storage"
    profiles_shortname = 'builder.cl_builder_profile_shortname'
    check_action = Actions.ChangeProfile

    @property
    def rep_names(self):
        dv = self.Get('cl_builder_linux_datavars')
        if dv:
            return dv.Get('cl_update_rep_name')
        return []


class VariableClBuilderProfileBranch(update.VariableClUpdateProfileBranch):
    """
    Текущая ветка репозитория
    """
    untrusted = True

    storage = "builder.cl_builder_profile_storage"
    url = "builder.cl_builder_profile_url"


class VariableClBuilderProfileData(update.VariableClProfileData):
    type = "table"
    source = ["cl_builder_profile_fullname",
              "cl_builder_profile_shortname",
              "cl_builder_profile_path",
              "cl_builder_profile_arch"]

    repository = "builder.cl_builder_profile_repository"

    def profile_filter(self, profiles):
        arch = self.Get('builder.os_builder_arch_machine_gentoo')
        return [x for x in profiles if x.arch == arch]


class VariableClBuilderProfileFullname(FieldValue, ReadonlyVariable):
    """
    Полное название профиля
    """
    type = "list"
    source_variable = "cl_builder_profile_data"
    column = 0


class VariableClBuilderProfileShortname(FieldValue, ReadonlyVariable):
    """
    Полное название профиля
    """
    type = "list"
    source_variable = "cl_builder_profile_data"
    column = 1


class VariableClBuilderProfilePath(FieldValue, ReadonlyVariable):
    """
    Полное название профиля
    """
    type = "list"
    source_variable = "cl_builder_profile_data"
    column = 2


class VariableClBuilderProfileArch(FieldValue, ReadonlyVariable):
    """
    Полное название профиля
    """
    type = "list"
    source_variable = "cl_builder_profile_data"
    column = 3


class VariableClBuilderProfileName(lib_linux.VariableClProfileName):
    """
    Install subname
    """
    source_var = "cl_builder_profile_system"

    def init(self):
        self.label = _("System profile")

    def get(self):
        action = self.Get('cl_action')
        if action == Actions.Prepare:
            source = self.Get('cl_builder_source')
            if isinstance(source, distr.ContainerDistributive):
                return source.get_information().get("cl_profile_name",
                                                    _("Unknown"))
        return super(VariableClBuilderProfileName, self).get()


class VariableClBuilderProfileRepoName(update.VariableClUpdateProfileRepoName):
    """
    Название репозитория
    """
    storage = "builder.cl_builder_profile_storage"
    url = "builder.cl_builder_profile_url"

    def humanReadable(self):
        return self.Get().capitalize()


class VariableClBuilderProfileRepository(
    update.VariableClUpdateProfileRepository):
    """
    Репозиторий из которого будет извлечён список профилей
    """
    type = "object"
    url = "builder.cl_builder_profile_url"
    storage = "builder.cl_builder_profile_storage"
    branch = "builder.cl_builder_profile_branch"


class VariableClBuilderTemplatesLocate(update.VariableClUpdateTemplatesLocate):
    """
    Выбранные типы хранилищ шаблонов
    """
    check_after = ['cl_builder_profile_system']

    profile_datevars = "builder.cl_builder_profile_datavars"


class VariableClBuilderProfileDatavars(update.VariableClUpdateProfileDatavars):
    type = "object"

    profile = "builder.cl_builder_profile_system_shortname"
    profiles_path = "builder.cl_builder_profile_path"
    profiles_shortname = "builder.cl_builder_profile_shortname"

    def get(self):
        profile = self.Get(self.profile)
        path_profile = self.Select(self.profiles_path,
                                   where=self.profiles_shortname,
                                   eq=profile, limit=1)
        # print self.Get(self.profiles_path)
        # print self.Get(self.profiles_shortname)
        # print profile
        builder_path = self.Get('cl_builder_path')
        # print "BUILDER_PATH", builder_path
        if path_profile:
            return DataVarsUpdateProfile(path_profile, builder_path)
        return ""


class VariableClBuilderProfileSystemShortname(
    update.VariableClUpdateProfileSystem):
    """
    Выбираемый профиль
    """
    opt = ["cl_builder_profile_system_shortname"]

    profiles_path = "builder.cl_builder_profile_path"
    profiles_shortname = "builder.cl_builder_profile_shortname"
    profiles_fullname = "builder.cl_builder_profile_fullname"
    profiles_arch = "builder.cl_builder_profile_arch"
    profile = "builder.cl_builder_profile_system"
    url = "builder.cl_builder_profile_url"
    gentoo_arch = 'builder.os_builder_arch_machine_gentoo'


class VariableOsBuilderArchMachineGentoo(
    lib_system.VariableOsArchMachineGentoo):
    """
    Архитектура пакетов
    """
    source_arch = "builder.os_builder_arch_machine"


class VariableClBuilderProfileLinuxFullname(
    update.VariableClUpdateProfileLinuxFullname):
    """
    Имя системы в профиле
    """
    datavars = "builder.cl_builder_profile_datavars"


class VariableClBuilderProfileDependData(
    update.VariableClUpdateProfileDependData):
    """
    Зависимые репозитории
    """
    source = ['cl_builder_profile_depend_name',
              'cl_builder_profile_depend_url']

    datavars = "cl_builder_profile_datavars"


class VariableClBuilderProfileDependName(FieldValue, ReadonlyVariable):
    type = "list"
    source_variable = "cl_builder_profile_depend_data"
    column = 0

    def init(self):
        self.label = _("Name")


class VariableClBuilderProfileDependUrl(FieldValue, ReadonlyVariable):
    type = "list"
    source_variable = "cl_builder_profile_depend_data"
    column = 1

    def init(self):
        self.label = _("URL")


class VariableClBuilderProfileSyncRep(ReadonlyVariable):
    type = "list"

    def get(self):
        return list(reversed(self.Get('update.cl_update_rep_name')))


class VariableClBuilderSyncRep(update.VariableClUpdateSyncRep):
    """
    Обновляемый репозиторий
    """

    @property
    def rep_name(self):
        dv = self.Get('cl_builder_linux_datavars')
        if dv:
            return dv.Get('cl_update_rep_name')
        return ""


class VariableClBuilderRemoveRep(ReadonlyVariable):
    def get(self):
        dv_builder_linux = self.Get('cl_builder_linux_datavars')
        dv_builder_profile = self.Get('cl_builder_profile_datavars')
        if dv_builder_linux and dv_builder_profile:
            return list(set(dv_builder_linux.Get('cl_update_rep_name')) -
                        set(dv_builder_profile.Get('cl_update_rep_name')))
        else:
            return []
