'''
Created on 5 lut 2020

@author: fpawlak
'''

from __future__ import print_function
import os
import sys
import errno
from Classes.CodesysLibsScriptsException import CodesysLibsScriptsException



class LibrariesInstaller():
    def __init__(self, libraryManager):
        self.libraryManager = libraryManager
     
     
    def getRepository(self, repositoryPreferences):
        try:
            try:
                print('Searching LibraryRepository: "{}"'.format(repositoryPreferences.name), end='')
                sys.stdout.flush()
                 
                repository = (repo for repo in self.libraryManager.repositories if repo.name == repositoryPreferences.name).next()
                print(' => FOUND')
            except StopIteration:
                try:
                    os.makedirs(repositoryPreferences.path, 0755)
                except OSError as e:
                    if not (e.errno == errno.EEXIST and os.path.isdir(repositoryPreferences.path)):
                        raise
                repository = self.libraryManager.insert_repository(repositoryPreferences.path, repositoryPreferences.name)
                print(' => NOT FOUND - Created new one at: {}'.format(repositoryPreferences.path))
             
            return repository
        except Exception as e:
            raise GetRepositoryException(e)
 
 
    def installLibs(self, repository, remoteRepositoryPath, aviableLibraries):
        print('Checking installed libraries:')
         
        try:
            for library in aviableLibraries.getLibraries():
                print('{}:'.format(library))
                 
                for version in aviableLibraries.getLibraryVersions(library):
                    print('[{}]'.format(version), end='')
                    sys.stdout.flush()
                     
                    lib = self.libraryManager.get_library(version, repository)
                    if lib == None:
                        print(' => installing', end='')
                        sys.stdout.flush()

                        if(self.libraryManager.install_library(remoteRepositoryPath + '\\' + aviableLibraries.getLibraryPath(library, version), repository, False) != None):
                            print(' => INSTALLED')
                        else:
                            print(' => ERROR')
                    else:
                        print(' => allready installed')
        except Exception as e:
            raise InstallLibException(e)
     
    def installLib(self, repository, libraryPath): 
        print('Installing library {}'.format(libraryPath), end='')
        sys.stdout.flush()

        if self.libraryManager.install_library(libraryPath, repository, True) != None:
            print(' => INSTALLED')
        else:
            print(' => ERROR')
                    
class GetRepositoryException(CodesysLibsScriptsException):
    pass

class InstallLibException(CodesysLibsScriptsException):
    pass
                