#!/usr/bin/env python

import os
import argparse
from niicat.plotter import plot
from pkg_resources import resource_filename
from pkg_resources import require

def is_executable(name):
    """Check whether `name` is on PATH and marked as executable."""
    from shutil import which
    return which(name) is not None


def main():
    parser = argparse.ArgumentParser(description="Generate previews of nifti image and png/jpeg images " +
                                                 "on the terminal.",
                                    epilog="Written by Jakob Wasserthal")
    parser.add_argument("nifti_file")
    parser.add_argument("-ic", action="store_true",
                        help="Use iTerm2's imgcat instead of libsixel-python to plot the image.",
                        default=False)
    parser.add_argument("-lb", action="store_true",
                        help="Use libsixel-bin instead of libsixel-python to plot the image.",
                        default=False)
    parser.add_argument("--dpi", metavar="N", type=int,
                        help="resolution for plotting (default: 150).",
                        default=150)
    parser.add_argument('--version', action='version', version=require("niicat")[0].version)
    args = parser.parse_args()


    if args.ic:
        niipre_path = resource_filename('niicat.resources', 'niipre_to_buffer.py')
        imgcat_path = resource_filename('niicat.resources', 'imgcat.sh')
        os.system("python " + niipre_path + " " + args.nifti_file + " " + str(args.dpi) + " | " + imgcat_path)
    elif args.lb:
        niipre_path = resource_filename('niicat.resources', 'niipre_to_buffer.py')
        imgcat_path = "img2sixel"
        if is_executable(imgcat_path):
            os.system("python " + niipre_path + " " + args.nifti_file + " " + str(args.dpi) + " | " + imgcat_path)
        else:
            print("ERROR: the command 'img2sixel' is not available in your PATH. " +
                  "Install libsixel-bin to make it available.")
    else:
        plot(args.nifti_file, dpi=args.dpi)


if __name__ == '__main__':
    main()
