#!/usr/bin/env python
#-*-coding:utf8-*-
import logging
import os
from datetime import timedelta
import tempfile
from .smb import PatchedSmbClient
log = logging.getLogger(__name__)


def getpath(filename=''):
    return os.path.join(os.path.dirname(__file__), filename)


class BaseConfig:
    NAME = 'default'
    # доступ к папке с конфигурацией
    PATH_TYPE = 'dir' # smb|dir|ftp

    SMB_SERVER = ''
    SMB_SHARE  = ''
    SMB_USER = ''
    SMB_PWD = ''

    # подключение к скл
    SQL_USER = 'sa'
    SQL_PWD = ''
    SQL_HOST = ''
    SQL_DB = ''

    # общий путь к папке с метаданными
    PATH_META = os.getenv('V7_PATH_META', os.path.join(tempfile.gettempdir(), 'v7_metadata'))
    # полный путь к папке метаданных 1С с учетом имени (для этой базы)
    PATH_META_DIR = ''
    # полный путь к моделям на py
    PATH_TO_MODEL = ''

    FILE_1Cv7_MD = u'1Cv7.MD'
    FILE_1Cv7_DDS = u'1Cv7.DDS'
    FILE_1Cv7_DBA = u'1Cv7.DBA'
    FILES = (FILE_1Cv7_MD, FILE_1Cv7_DDS, FILE_1Cv7_DBA)
    # абсолютные пути к файлам после инициализации
    PATH_1Cv7_MD = ''
    PATH_1Cv7_DDS = ''
    PATH_1Cv7_DBA = ''

    # update metadata interval
    UPDATE_INTERVAL = None  # timedelta(days=1)

    def __init__(self):
        self.init_config()

    def METAFILE_FULL_PATH(self, filename):
        return os.path.join(self.PATH_META_DIR, filename)

    def init_config(self):
        self.PATH_META_DIR = os.path.join(self.PATH_META, self.NAME)
        self.PATH_TO_MODEL = os.path.join(self.PATH_META_DIR, 'model')
        self.PATH_1Cv7_DBA = self.METAFILE_FULL_PATH(self.FILE_1Cv7_DBA)
        self.PATH_1Cv7_DDS = self.METAFILE_FULL_PATH(self.FILE_1Cv7_DDS)
        self.PATH_1Cv7_MD = self.METAFILE_FULL_PATH(self.FILE_1Cv7_MD)
        for dirpath in (self.PATH_META_DIR, self.PATH_TO_MODEL):
            if not os.path.exists(dirpath):
                log.info(u'Create dir for %s=%s' % (self.__class__.__name__, dirpath))
                os.makedirs(dirpath)

    def update_meta_files(self):
        #ToDo добавить лок для скачивание только одним потоком
        log.info(u'Start update meta files: %s' % self.__unicode__())
        if self.PATH_TYPE == 'smb':
            smb = PatchedSmbClient(server=self.SMB_SERVER, share=self.SMB_SHARE, username=self.SMB_USER, password=self.SMB_PWD)
            #print smb.listdir('/')
            workdir = smb.listdir(self.PATH_TO_BASE)
            log.debug(u'Files on smb: %s' % repr(workdir))
            for filename in self.FILES:
                if filename in workdir:
                    fullname = os.path.join(self.PATH_TO_BASE, filename)
                    target_name = self.METAFILE_FULL_PATH(filename)
                    log.info(u'downloading: %s -> %s' % (fullname, target_name))
                    smb.download(fullname, target_name)
            return True

        if self.PATH_TYPE == 'dir':
            workdir = os.listdir(self.PATH_TO_BASE)
            log.debug(u'Files on smb: %s' % repr(workdir))
            for filename in self.FILES:
                if filename in workdir:
                    fullname = os.path.join(self.PATH_TO_BASE, filename)
                    target_name = self.METAFILE_FULL_PATH(filename)
                    log.info(u'copying: %s -> %s' % (fullname, target_name))
                    fsrc = open(fullname, 'rb', 1024)
                    try:
                        fout = open(target_name, 'wb', 1024)
                        fout.write(fsrc.read())
                    finally:
                        fsrc.close()
                        fout.close()
            return True

    def __unicode__(self):
        return u"1Cv7 config[%s]: %s path: %s type: %s" % (self.__class__.__name__, self.NAME, self.PATH_TO_BASE, self.PATH_TYPE)
