"""
disk and partition functions for dmm.
"""

import pathlib
from command_runner import command_runner

def run_parted_commands(disk, command):
    """
    Iterate through parted commands and return an error if applicable.
    """
    ecode, result = command_runner("parted -s -- %s %s" % (disk, command))
    return ecode, result


def run_parted_command_set(command_set):
    """
    Iterate through a set of parted commands and return an error if applicable.
    """
    #print(command_set)
    for partition in command_set:
        #print("")
        #print("Command: ", partition)
        #print("action-type: ", partition['action-type'])
        #print("command: ", partition['action-type'])
        #print(repr(("device: ", partition['device'])))
        #print(partition['device'], partition['command'])
        ecode, result = run_parted_commands(partition['device'], partition['command'])
        ecode, result =  command_runner("mkfs.%s %s" % (partition['fstype'], partition['partition'])) 
        if partition["espflag"]:
            # FIXME: Unhardcode
            ecode, result = command_runner("parted -s -- set 1 esp on")
        print (ecode, result)
    return ecode, result 


def initialize_gpt_table(disk):
    """
    Create a new GPT partition table on the device.
    """
    command_runner("wipefs -a %s" % (disk))
    ecode, result = command_runner("sgdisk -o %s" % (disk))
    return ecode, result


def losetup(diskimg, mountpoint, loopdev):
    """
    Sets up a loopback device.
    """
    ecode, result = command_runner("losetup -P /dev/%s %s" % (loopdev, diskimg))
    return ecode, result


def losetup_teardown(loopdev):
    """
    Unmounts a loopback device.
    """
    ecode, result = command_runner("losetup -d /dev/%s" % (loopdev))
    return ecode, result


def create_filesystems(partitions):
    """
    Creates a new filesystem on a device.
    """
    for partition in partitions:
        ecode, result = command_runner("mkfs.%s %s %s" % (partition['fstype'], partition['options'], partition['partition']))
        if ecode != 0:
            return ecode, result


def mount(filesystems):
    """
    Mounts filesystems
    """
    for filesystem in filesystems:
        path = pathlib.Path(filesystem['mountpoint'])
        path.mkdir(parents=True, exist_ok=True)
        ecode, result = command_runner("mount -t %s %s %s %s" % (filesystem['fstype'], filesystem['mountopts'],
                  filesystem['source'], filesystem['mountpoint']))
        if ecode != 0:
            return ecode, result
    return ecode, result


def umount(mounts):
    """
    Unmounts filesystems
    """
    for mount in mounts:
        path = pathlib.Path(mount['mountpoint'])
        ecode, result = command_runner("umount %s" % (mount['mountpoint']))
        if ecode != 0:
            return ecode, result
    return ecode, result
