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

# Copyright 2008-2013 Calculate Ltd. 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, re
import xml.dom.minidom
from calculate.lib.utils.common import _error
from calculate.lib.utils.files import process,STDOUT

from calculate.lib.cl_lang import setLocalTranslate
setLocalTranslate('cl_lib3',sys.modules[__name__])

class diff(_error):
    """
    Format using diff
    """
    text = ""

    def __init__(self, text):
        self.text = text

    def textToXML(self):
        return self.text

    def processingFile(self, textConfigFile, rootPath=None):
        self.patchFiles = []
        retTextConfigFile = textConfigFile
        for i in range(0,4):
            patchDryRun = process('/usr/bin/patch','--dry-run',
                      '-p%d'%i,cwd=rootPath,)
            patchDryRun.write(self.text)
            if patchDryRun.success():
                break
            patchDryRun = process('/usr/bin/patch','-R','--dry-run',
                      '-p%d'%i,cwd=rootPath,)
            patchDryRun.write(self.text)
            if patchDryRun.success():
                return ""
        else:
            self.setError(_("Correction failed"))
            return False
        patchRun = process('/usr/bin/patch',
                  '-p%d'%i,cwd=rootPath)
        patchRun.write(self.text)
        if patchRun.success():
            for line in patchRun:
                if line.startswith("patching file"):
                    self.patchFiles.append(line[13:].strip())
            return patchRun.read()
        return ""
