#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import cv2
import numpy as np
from sys import float_info

import time


def clip(x, up, low):
    if up < low:
        up, low = low, up
    return max(low, min(up, x))


def cvt_line(rho, theta, shape):
    r, t = rho, theta
    h, w = shape[:2]
    h -= 1
    w -= 1
    sin = np.sin
    cos = np.cos
    if abs(cos(t)) > cos(np.radians(45)):
        x1 = r/cos(t)
        x2 = (rho - h * sin(t))/cos(t)
        x1 = clip(x1, 0, w)
        x2 = clip(x2, 0, w)

        if abs(sin(t)) > float_info.epsilon:  # 0
            y1 = (r - x1 * cos(t))/sin(t)
            y2 = (r - x2 * cos(t))/sin(t)
        else:
            y1 = 0
            y2 = h
        y1 = clip(y1, 0, h)
        y2 = clip(y2, 0, h)
    else:
        y1 = r/sin(t)
        y2 = (r - w * cos(t))/sin(t)
        y1 = clip(y1, 0, h)
        y2 = clip(y2, 0, h)

        if abs(cos(t)) > float_info.epsilon:  # 0
            x1 = (rho - y1 * sin(t))/cos(t)
            x2 = (rho - y2 * sin(t))/cos(t)
        else:
            x1 = 0
            x2 = w
        x1 = clip(x1, 0, w)
        x2 = clip(x2, 0, w)

    x1 = int(round(x1))
    x2 = int(round(x2))
    y1 = int(round(y1))
    y2 = int(round(y2))

    return (x1, y1), (x2, y2)


def mid_point(line, shape):
    rho, theta = line
    pt1, pt2 = cvt_line(rho, theta, shape)

    x1, y1 = pt1
    x2, y2 = pt2

    return (x1 + x2)/2, (y1 + y2)/2


def line_dist(l1, l2, shape):
    m1 = mid_point(l1, shape)
    m2 = mid_point(l2, shape)
    return np.sqrt(
            np.power(m1[0] - m2[0], 2) +
            np.power(m1[1] - m2[1], 2)
            )


def intersection(horizontal, vertical, shape):
    height = shape[0]
    width = shape[1]

    if abs(vertical[1]) > float_info.epsilon:
        vertical1 = 0, vertical[0]/np.sin(vertical[1])
        vertical2 = width, -width/np.tan(vertical[1]) + vertical1[1]