# Create a mask from annotation.  Uses the same ROI as download region.


import sys
import os
import pdb
import girder_client
import json
import urllib2
import numpy as np
import scipy
import cv2
import math


def ensure_path(dir_path):
    parent, name = os.path.split(dir_path)
    if name == '':
        return
    ensure_path(parent)
    ensure_dir(dir_path)

def ensure_dir(dir_path):
    if not os.path.exists(dir_path):
        os.makedirs(dir_path)

# first and last point should be repeated.
# scan line approach
def fill_polygon(image, points, color):
    (xdim, ydim) = image.shape;
    xmax = xdim-1
    ymax = ydim-1
    # find the bounds of the poygon.
    bds = [xmax, 0, ymax, 0]
    for pt in points:
        x = int(math.floor(pt[0]))
        if x < bds[0]:
            bds[0] = x
        x = int(math.ceil(pt[0]))
        if x > bds[1]:
            bds[1] = x
        y = int(math.floor(pt[1]))
        if y < bds[2]:
            bds[2] = y
        y = int(math.ceil(pt[1]))
        if y > bds[3]:
            bds[3] = y
    if bds[0] < 0:
        bds[0] = 0
    if bds[1] > xmax:
        bds[1] = xmax
    if bds[2] < 0:
        bds[2] = 0
    if bds[3] > ymax:
        bds[3] = ymax