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

# Copyright 2008-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 os import path
import bz2
import os
import shutil
from .files import readFile, listDirectory

class VardbPackage():
    """
    Объект для модификации пакета из /var/db/pkg
    """
    def __init__(self, infodn):
        self.infodn = infodn
        self.CATEGORY, self.PF = path.split(infodn)
        self.CATEGORY = path.basename(self.CATEGORY)
        self.environment = path.join(self.infodn, "environment.bz2")
        self.depend = path.join(self.infodn, "DEPEND")
        self.bdepend = path.join(self.infodn, "BDEPEND")
        self.depend_binary = path.join(self.infodn, "DEPEND.binary")
        self.bdepend_binary = path.join(self.infodn, "BDEPEND.binary")
        self.detected_mark = path.join(self.infodn, "EMERGE_FROM")

    def __repr__(self):
        return "%s/%s"%(self.CATEGORY, self.PF)

    def set_detected(self, binary):
        with open(self.detected_mark, 'w') as f:
            f.write("binary" if binary else "ebuild")

    @property
    def binary(self):
        # detect by mark file
        if path.exists(self.detected_mark):
            return readFile(self.detected_mark).strip() == "binary"
        # detect by old detect
        if path.exists(self.bdepend_binary) or path.exists(self.depend_binary):
            self.set_detected(True)
            return True
        buf = None
        # detect by environment.bz2
        with bz2.BZ2File(self.environment, 'r') as f:
            for n in range(0,3):
                if buf is None:
                    buf = f.read(10000)
                else:
                    buf += f.read(10000)
                if b"isz=" in buf:
                    self.set_detected(True)
                    return True
        self.set_detected(False)
        return False

    def hide_depends(self):
        for dep, depb in [(self.depend, self.depend_binary),
                          (self.bdepend, self.bdepend_binary)]:
            if path.exists(dep):
                os.rename(dep, depb)

    def unhide_depends(self):
        for dep, depb in [(self.depend, self.depend_binary),
                          (self.bdepend, self.bdepend_binary)]:
            if path.exists(depb):
                os.rename(depb, dep)


class Vardb():
    """
    Объект для получения пакетов из /var/db/pkg
    """
    def __init__(self, dbdn):
        self.dbdn = dbdn

    def __iter__(self):
        for category in listDirectory(self.dbdn, fullPath=True):
            if path.isdir(category):
                for pkg in listDirectory(category, fullPath=True):
                    if "MERGING-" not in pkg and  path.isdir(pkg):
                        yield VardbPackage(pkg)

    def hide_binary_depends(self):
        for pkg in self:
            if pkg.binary:
                pkg.hide_depends()

    def unhide_binary_depends(self):
        for pkg in self:
            if pkg.binary:
                pkg.unhide_depends()
