# coding: UTF-8
'''
Created 28.02.2016 by s.gavrilov
'''
from array import array
from datetime import datetime
from java.io import FileOutputStream, BufferedInputStream, FileInputStream
import os
import zipfile
from common.grainssettings import SettingsManager
from common.numbersseries.getNextNo import getNextNoOfSeries
from fileRepository._fileRepository_orm import fileCounterCursor, \
    fileCursor, fileVersionCursor
from common._common_orm import linesOfNumbersSeriesCursor


try:
    from ru.curs.showcase.core.jython import JythonDTO, JythonDownloadResult
except:
    from ru.curs.celesta.showcase import JythonDTO, JythonDownloadResult

import shutil
from bs4 import BeautifulSoup
import codecs

def unzipFileIntoRepository(context, fileName, file, folder):
    grains_settings_XML = SettingsManager(context)
    fileRepositoryPath = grains_settings_XML.getGrainSettings(
    "clusterPath/cluster", "fileRepository")
    raise Exception(fileRepositoryPath)
    pathToZip = os.path.join(fileRepositoryPath[0], fileName)
    
    fileToWrite = FileOutputStream(pathToZip)
    size_of_file = 0
    stream_size = 4096
    buffer_stream = BufferedInputStream(file, stream_size)
    d = array("b", [0] * stream_size)
    c = buffer_stream.read(d, 0, stream_size)
    while c != -1:
        fileToWrite.write(d[:c])
        size_of_file += 1
        c = buffer_stream.read(d, 0, stream_size)
    buffer_stream.close()
    fileToWrite.close()
    try:
        zip_ref = zipfile.ZipFile(pathToZip, 'r')
        extractPath = os.path.join(fileRepositoryPath[0], folder, fileName)
        zip_ref.extractall(extractPath)
        zip_ref.close()
    except:
        context.error(u"Файл не соответствует расширению *.zip!")
    finally:
        os.remove(pathToZip)
    resultFolder = "/".join([os.path.basename(os.path.normpath(fileRepositoryPath[0])), folder, fileName, "index.html"])
    return resultFolder
    
def deleteByRef(context, path):
    grains_settings_XML = SettingsManager(context)
    fileRepositoryPath = grains_settings_XML.getGrainSettings(
    "clusterPath/cluster", "fileRepository")
    path = path.replace(os.path.basename(os.path.normpath(fileRepositoryPath[0])), "").replace("index.html", "")

    refPath = path.split("/")
    refPath.pop()
    if (len(refPath) > 0):
        folderToDelete = os.path.join(fileRepositoryPath[0], *refPath)
        if (os.path.isdir(folderToDelete)):
            shutil.rmtree(folderToDelete)