import datetime
import os
from time import sleep

from icloudpy import ICloudPyService, exceptions, utils

from src import (
    DEFAULT_CONFIG_FILE_PATH,
    DEFAULT_COOKIE_DIRECTORY,
    ENV_CONFIG_FILE_PATH_KEY,
    ENV_ICLOUD_PASSWORD_KEY,
    LOGGER,
    config_parser,
    read_config,
    sync_drive
)


def get_api_instance(
    username,
    password,
    cookie_directory=DEFAULT_COOKIE_DIRECTORY,
    server_region="global",
):
    return (
        ICloudPyService(
            apple_id=username,
            password=password,
            cookie_directory=cookie_directory,
            home_endpoint="https://www.icloud.com.cn",
            setup_endpoint="https://setup.icloud.com.cn/setup/ws/1",
        )
        if server_region == "china"
        else ICloudPyService(
            apple_id=username,
            password=password,
            cookie_directory=cookie_directory,
        )
    )

def sync():
    last_send = None
    enable_sync_drive = True
    drive_sync_interval = 0
    sleep_for = 10
    while True:
        config = read_config(
            config_path=os.environ.get(
                ENV_CONFIG_FILE_PATH_KEY, DEFAULT_CONFIG_FILE_PATH
            )
        )
        username = config_parser.get_username(config=config)
        if username:
            try:
                if ENV_ICLOUD_PASSWORD_KEY in os.environ:
                    password = os.environ.get(ENV_ICLOUD_PASSWORD_KEY)
                    utils.store_password_in_keyring(
                        username=username, password=password
                    )
                else:
                    password = utils.get_password_from_keyring(username=username)
                server_region = config_parser.get_region(config=config)
                api = get_api_instance(
                    username=username, password=password, server_region=server_region
                )


                if not api.requires_2sa:               

                    if "drive" in config and enable_sync_drive:
                        LOGGER.info("Синхронизация drive...")
                        vvvv = sync_drive.sync_drive(config=config, drive=api.drive, work=api.work)
                        LOGGER.info("Drive синхронизирован")
                        my_file = open("last_update.txt", "w")
                        my_file.write(datetime.datetime.now().isoformat())
                        my_file.close()
                        drive_sync_interval = config_parser.get_drive_sync_interval(
                            config=config
                        )
                   
                    if "drive" not in config:
                        LOGGER.warning(
                            "Нечего синхронизировать. Добавьте раздел drive в файл config.yaml."
                        )
                else:
                    LOGGER.error("Ошибка: требуется 2FA. Пожалуйста, войдите в систему.")
              
                    sleep_for = config_parser.get_retry_login_interval(config=config)
                    next_sync = (
                        datetime.datetime.now() + datetime.timedelta(seconds=sleep_for)
                    ).strftime("%c")
                    if sleep_for < 0:
                        LOGGER.info("retry_login_interval is < 0, exiting ...")
                        break
                    LOGGER.info(f"Повторная попытка входа в {next_sync} ...")
                    sleep(sleep_for)
                    continue
            except exceptions.ICloudPyNoStoredPasswordAvailableException:
                LOGGER.error(
                    "Пароль не сохранен в связке ключей. Пожалуйста, сохраните пароль в связке ключей."
                )
                sleep_for = config_parser.get_retry_login_interval(config=config)
                next_sync = (
                    datetime.datetime.now() + datetime.timedelta(seconds=sleep_for)
                ).strftime("%c")
                LOGGER.info(f"Повторная попытка входа в систему {next_sync} ...")

                sleep(sleep_for)
                continue
    
        if "drive" in config:
            sleep_for = drive_sync_interval
            enable_sync_drive = True
            enable_sync_photos = False
       
        next_sync = (
            datetime.datetime.now() + datetime.timedelta(seconds=sleep_for)
        ).strftime("%c")
        LOGGER.info(f"Повторная синхронизация в {next_sync} ...")
        if (
            config_parser.get_drive_sync_interval(config=config) < 0
            if "drive" in config
            else True and config_parser.get_photos_sync_interval(config=config) < 0           
        ):
            break
        sleep(sleep_for)
