# coding=utf-8
import json
import logging
import sys

import networkx
import pytest

from bireus.client.download_service import DownloadError
from bireus.client.repository import ClientRepository, CheckoutError
from bireus.server.repository_manager import RepositoryManager
from bireus.shared import *
from bireus.shared.repository import ProtocolException
from tests import assert_file_equals, assert_zip_file_equals
from tests.create_test_server_data import create_test_server_data
from tests.mocks.mock_download_service import MockDownloadService

root = logging.getLogger()
root.setLevel(logging.DEBUG)

ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)-25s - %(levelname)-5s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)

server_path = Path.cwd().joinpath("example-server")
client_path = Path.cwd().joinpath("example-client")
test_url = "http://localhost:12345/subfolder/subsub"


@pytest.fixture()
def prepare_server():
    # create demo repo
    create_test_server_data(server_path, "inst-bi")
    RepositoryManager(server_path).full_update()
    if client_path.exists():
        remove_folder(client_path)

    yield prepare_server

    # teardown


def get_latest_version(mocker, downloader) -> ClientRepository:
    global client_repo

    downloader.add_read_action(lambda url: server_path.joinpath("repo_demo", "info.json").read_bytes())
    version_graph = server_path.joinpath("repo_demo", "versions.gml")
    server_latest = server_path.joinpath("repo_demo", "latest.tar.xz")
    downloader.add_download_action(lambda path_from, path_to: copy_file(version_graph, path_to))
    downloader.add_download_action(lambda path_from, path_to: copy_file(server_latest, path_to))

    return ClientRepository.get_from_url(client_path, test_url, downloader, file_logging=False)


def test_get_from_url_folder_exists():
    Path("example-client").mkdir(exist_ok=True)