#!/usr/bin/env python3
# summary: Manage file sharing, network folders, and connected accounts.
"""Files' everyday actions: sharing, network computers, accounts and earlier versions."""
import os
from pathlib import Path
import subprocess
import sys
sys.path.insert(0, str(Path(__file__).resolve().parent))
from starchaser_files_common import gtk, dialog, launch, atomic_json, read_json

SUGGESTIONS = {'.docx': ('Word documents', 'LibreOffice'), '.doc': ('Word documents', 'LibreOffice'), '.xlsx': ('Excel spreadsheets', 'LibreOffice'), '.xls': ('Excel spreadsheets', 'LibreOffice'), '.pptx': ('PowerPoint presentations', 'LibreOffice'), '.odt': ('documents', 'LibreOffice'), '.rar': ('RAR archives', 'Archive Manager'), '.epub': ('e-books', 'Foliate'), '.pdf': ('PDF documents', 'Document viewer')}


def suggestion(path):
    return SUGGESTIONS.get(Path(path).suffix.lower(), ('this kind of file', ''))


def missing(path):
    kind, app = suggestion(path)
    name = Path(path).name
    text = f'Nothing here opens “{name}” yet.' + (f' {app} opens {kind}.' if app else ' Find an app in Software or choose an installed app.')
    answer = dialog('Find an app for this file', text, ['Cancel', f'Get {app}' if app else 'Find an app in Software', 'Choose an app…'])
    if answer == 1:
        catalog = {'LibreOffice': 'libreoffice', 'Document viewer': 'papers'}.get(app)
        launch('starchaser', 'settings', 'app' if catalog else 'search', catalog or app or Path(path).suffix.lstrip('.'))
    elif answer == 2:
        launch('flea', '--open-with', path)


def versions_for(path, snapshots=Path('/.snapshots')):
    path = Path(path).absolute()
    rows = []
    for root in sorted(Path(snapshots).glob('*/snapshot'), reverse=True):
        candidate = root / str(path).lstrip('/')
        try:
            if candidate.is_file() and not candidate.is_symlink():
                rows.append(candidate)
        except OSError:
            continue
    return rows


def restore_copy(source, destination):
    # Earlier versions never overwrite the current file. O_EXCL also handles a racing copy or a symlink.
    import shutil
    destination = Path(destination)
    name = destination.stem + ' (earlier version)'
    for number in range(1, 10000):
        target = destination.with_name(name + (f' {number}' if number > 1 else '') + destination.suffix)
        try:
            fd = os.open(target, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
        except FileExistsError:
            continue
        try:
            with os.fdopen(fd, 'wb') as output, open(source, 'rb') as stream:
                shutil.copyfileobj(stream, output)
                output.flush()
                os.fsync(output.fileno())
        except Exception:
            target.unlink(missing_ok=True)
            raise
        return target
    raise ValueError('There are too many earlier copies in this folder.')



def preset(profile):
    value = {'macos': 'mac', 'windows': 'windows', 'vim': 'vim'}.get(profile, 'default')
    import json
    subprocess.run(['flea', '--ui-state', json.dumps({'keys': value})], capture_output=True, check=True)
    return value


def main(args):
    if not args or args[0] in ('--help', '-h'):
        print(__doc__)
        return 0
    action, paths = args[0], args[1:]
    if paths[:1] == ['--from-settings']:          # pressed in Settings > Sharing: its notices come from Settings
        import starchaser_files_common
        starchaser_files_common.NOTICE_APP = 'Settings'
        paths = paths[1:]
    if action == 'missing' and len(paths) == 1:
        missing(paths[0])
    elif action == 'ensure-share':
        # Kept for a sign-in unit from before decision 76: it only reports, it never downloads.
        return 0 if subprocess.run(['flatpak', 'info', 'org.localsend.localsend_app'], capture_output=True).returncode == 0 else 1
    elif action == 'nearby-status':
        import json
        from starchaser_files_share import status
        print(json.dumps(status()))
    elif action == 'stop-receiving':
        from starchaser_files_share import stop_receiving
        stop_receiving()
    elif action == 'allow-firewall':
        from starchaser_files_share import firewall_draft
        firewall_draft()
    elif action == 'nearby-list':
        import json
        from starchaser_files_share import discover
        print(json.dumps(discover()))
    elif action == 'receive':
        from starchaser_files_share import allow_receiving
        allow_receiving()
    elif action == 'share' and paths:
        from starchaser_files_share import share
        share(paths)
    elif action == 'network-list':
        import json
        from starchaser_files_network import discovered
        print(json.dumps(discovered()))
    elif action == 'network':
        from starchaser_files_network import connect
        connect()
    elif action == 'mount' and paths:
        from starchaser_files_network import mount
        return 0 if mount(paths[0], sys.stdin.readline().rstrip('\n')) else 1
    elif action == 'accounts':
        from starchaser_files_accounts import accounts
        accounts()
    elif action == 'restore-cloud':
        from starchaser_files_accounts import restore_mounts
        restore_mounts()
    elif action == 'versions' and len(paths) == 1:
        launch('starchaser', 'versions', 'show', paths[0])
    elif action == 'preset' and len(paths) == 1:
        print(preset(paths[0]))
    elif action == 'unlock-drive' and len(paths) == 1:
        from starchaser_files_devices import unlock_drive
        unlock_drive(paths[0])
    elif action == 'drives':
        from starchaser_files_devices import drives
        drives()
    elif action == 'eject-folder' and len(paths) == 1:
        import runpy
        auto = runpy.run_path(str(Path(__file__).resolve().with_name('starchaser-automount')))
        objects = auto['managed_objects']()
        selected = next((data[auto['BLOCK']]['Device'] for data in objects.values() if paths[0] in data.get(auto['FILESYSTEM'], {}).get('MountPoints', [])), '')
        if selected:
            from starchaser_files_devices import eject
            return 0 if eject(selected) else 1
    elif action == 'eject' and len(paths) == 1:
        from starchaser_files_devices import eject
        return 0 if eject(paths[0]) else 1
    elif action == 'watch-phones':
        from starchaser_files_devices import watch_phones
        watch_phones()
    elif action == 'help':
        dialog('Files Help', 'Open: double-click, or Enter.\nFind a file here: just start typing.\nSearch everywhere: Ctrl+F. Inside files: Ctrl+G.\nRight-click a file for Share, Properties and more (Shift+F10).\nUndo the last change: Ctrl+Z.\nAll keys: press ?', ['Close'])
    else:
        return 2
    return 0


if __name__ == '__main__':
    try:
        sys.exit(main(sys.argv[1:]))
    except (ValueError, OSError, subprocess.SubprocessError) as error:
        message = str(error) if type(error) is ValueError else 'Check your connection and try again. Your existing files have been kept.'
        dialog('Files could not finish', message, ['Close'])
        sys.exit(1)
