#!/usr/bin/env python

import argparse
import sys
import time

import numpy as np
from skimage import img_as_float
from skimage.color import rgb2gray
from skimage.measure import block_reduce
from skimage.io import imread

def save_cursor_position(file=sys.stdout):
    print("\033[s", file=file, end="")


def restore_cursor_position(file=sys.stdout):
    print("\033[u", file=file, end="")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description="Plot image in ascii"
    )

    parser.add_argument(
        "--pool",
        type=int,
        default=1,
        help="Pool to reduce the size of the image"
    )
    parser.add_argument(
        "--vmin",
        metavar="V",
        type=float,
        default=0,
        help="Treat values smaller or equal to V as 0"
    )
    parser.add_argument(
        "--vmax",
        metavar="V",
        type=float,
        default=1,
        help="Treat values larger or equal to V as 1"
    )
    parser.add_argument(
        "--delay", "-d",
        type=lambda x: float(x)/1000,
        default=0.2,
        help="Delay between frames in milliseconds"
    )
    parser.add_argument(
        "input",
        help="The input image"
    )

    args = parser.parse_args()

    if args.input == "-":
        images = [l.strip() for l in sys.stdin]
    else:
        images = [args.input]

    previous = 0
    save_cursor_position()
    for i, im in enumerate(images):
        restore_cursor_position()

        img = imread(im)
        if len(img.shape) == 3 and img.shape[2] >= 3:
            img = rgb2gray(img)
        if args.pool > 1:
            img = block_reduce(img, (args.pool,)*2, np.max)
        img = (img_as_float(img) - args.vmin) / (args.vmax - args.vmin)
        np.clip(img, 0, 1-1e-6, img)

        c = time.time()
        if c-previous < args.delay:
            time.sleep(args.delay - c + previous)
        scale = np.array(list(" .:-=+*#%@"))
        levels = len(scale)
        for row in img:
            print("".join(scale[(row*levels).astype(int)]))
        if len(images) > 1:
            print()
            print("Frame", i, "/", len(images))
        previous = time.time()
