#!/usr/bin/env python
# -*- coding: UTF-8 -*-

"""Client-server application for syncing local folders with remote server.
"""

import os
import re

__author__ = "Peter Boba"
__license__ = "GPL"
__version__ = "3"
__maintainer__ = "Peter Boba"
__email__ = "peterbobajr@gmail.com"
__status__ = "Development"


def get_base_file_path(file_path, folder_path):
    """
    Given the file full abs path and the folder path,
    this function will return the base path of the file.
    This means the file path minus the folder path + basename
    :param file_path
    :param folder_path
    :return: base path of the file
    """
    basename = folder_path.split(os.path.sep)[-1] if folder_path.split(os.path.sep)[-1] else ""
    common = os.path.commonprefix([file_path, folder_path])
    return basename + file_path.replace(common, '')


def add_file_to_server(username, base_path, payload, server_path):
    # Get the folder path
    folder_path = os.path.sep.join(base_path.split(os.path.sep)[:-1]).lstrip(os.path.sep)
    file_name = base_path.split(os.path.sep)[-1]
    print folder_path, file_name
    try:
        # Ignore exceptions of makedirs
        os.makedirs(os.path.join(server_path, username, folder_path))
    except OSError:
        pass
    try:
        if os.path.exists(os.path.join(server_path, username, folder_path)):
            with open(os.path.join(server_path, username, folder_path, file_name), 'wb') as output:
                output.write(payload)
    except OSError as e:
        print e
        return False
    return True


def remove_file_from_server(username, base_path, server_path):
    # Get the file path
    file_path = os.path.join(server_path, username, base_path)
    if os.path.exists(file_path):
        try:
            os.remove(file_path)
        except OSError:
            return False
    return True


def setting_validate(settings, ui=None):
    valid = True
    # Validate server ip
    ip = re.compile("^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
    if not (ip.match(settings.server_ip) or settings.server_ip == 'localhost'):
        if ui:
            ui.statusbar.showMessage('IP Address %s not valid' % settings.server_ip, 3000)
        valid = False
    # Validate sync freq
    if not (settings.sync_freq > 3) and (settings.sync_freq < 20000):
        if ui:
            ui.statusbar.showMessage('Sync frequency %d not valid' % settings.sync_freq, 3000)
        valid = False
    # Validate port
    if not (settings.port > 0) and (settings.port <= 65535):
        if ui:
            ui.statusbar.showMessage('Port %d not valid' % settings.port, 3000)
        valid = False

    # Check if user and password are set
    if settings.user == "" or settings.password == "":
        if ui:
            ui.statusbar.showMessage("Username or password not set", 3000)
        valid = False
    print settings
    if not valid:
        return

    return settings


if __name__ == "__main__":
    # Test the get file path fnc
    print get_base_file_path('/home/cakeisalie/workspace/dir_sync/test/test_folder1/file1',
                             '/home/cakeisalie/workspace/dir_sync/test/test_folder1')
    print get_base_file_path('/apps/staging/hello_world/bla/bla/bla/file.txt', '/apps/staging/hello_world/bla/bla')
    print get_base_file_path('/apps/staging/hello_world/bla/bla/bla/file.txt', '/apps/staging/hello_world/bla')
    print get_base_file_path('/apps/staging/hello_world/bla/bla/bla/file.txt', '/apps/staging/hello_world/bla/bla/bla')
    from app.app_config import SERVER_STORAGE
    add_file_to_server('pexip', '/fdsfs/dsfsd/sasa', 'dsadsad', SERVER_STORAGE)
