# -*- 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 re
import sys
from calculate.update.emerge_parser import EmergeInformationBlock
from calculate.lib.utils.portage import EmergePackage

_ = lambda x: x
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)

setLocalTranslate('cl_builder3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)


class EmergePackageFetch(EmergePackage):
    files = []


class EmergeFetcherError(Exception):
    class FetchErrno():
        Generic = 0
        Lock = 1
        NeedManually = 2

    def __init__(self, message, errno=FetchErrno.Generic, extension=""):
        super().__init__(message)
        self.errno = errno
        self.extension = extension


class EmergeFetcher():
    _color_block = EmergeInformationBlock._color_block
    _new_line = EmergeInformationBlock._new_line
    re_fetching = re.compile(
        ">>> Fetching \({c}\d+{c} of {c}\d+{c}\) {c}(.*?){c}{nl}(.*?)"
        "(?=>>> Fetching|$)".format(c=_color_block, nl=_new_line), re.S)

    re_filename = re.compile("^{c} [*] {c}(\S+).*;-\)".format(c=_color_block),
                             re.M)

    lock_token = "is already locked by another fetcher"
    manually_token = "to be downloaded manually"

    def __init__(self, emerge_command):
        """
        :param emerge_command: команда emerge
        :return:
        """
        self.emerge_command = emerge_command

    def parse(self, data):
        if self.lock_token in data:
            raise EmergeFetcherError(
                _("File is already locked by another fetcher."),
                errno=EmergeFetcherError.FetchErrno.Lock)
        if self.manually_token in data:
            extension = re.search(
                "{nl}( {c}\*{c} The driver.*to be downloaded.*?)"
                "{nl}{nl}".format(c=self._color_block,
                                  nl=self._new_line), data, re.S)
            if extension:
                extension = extension.group(1)
            else:
                extension = ""
            raise EmergeFetcherError(
                _("File must be downloaded manually."),
                errno=EmergeFetcherError.FetchErrno.NeedManually,
                extension=extension)
        for package, block in self.re_fetching.findall(data):
            ep = EmergePackageFetch(package)
            ep.files = [x for x in self.re_filename.findall(block)]
            yield ep

    def __iter__(self):
        child = self.emerge_command.execute()
        for i in self.parse(child.read()):
            yield i

    def success(self):
        return self.emerge_command.success()

    def failed(self):
        return self.emerge_command.failed()
