'''
Created on 20-Jan-2022

@author: bthakur
'''

import inspect
import traceback
import random
import numpy as np
from sympy import (Polygon, latex, 
                   sin, cos, 
                   pi
                   )


from xv.km.util import latex_fraction
from sympy.core.expr import UnevaluatedExpr

from xv.km.ui import SvgHelper
from xv.util.data import CacheUtil

import matplotlib.pyplot as plt
from xv.plotter.core import Plotter2D, Plotter3D

from xv.util import toIntOrFloat

# _polygon_helper
# PolygonHelper

class PolygonHelper:
    _MAIN_OPACITY = 1
    _SUB_OPACITY = 0.3
    
    def __init__(self, **kwargs):
        self.verbose = kwargs.get('verbose', False)
        pass


    
    def get_random_triangle(self, b, h, theta, left_bottom = (0, 0)):
        p1 = np.array(left_bottom)
        p2 = p1 + np.array((b, 0))
        
        n3 = toIntOrFloat(h / np.sin(float(theta)), roundoff =  2)
        
        p3 = p1 + np.array((n3 * cos(float(theta)), h)) 
        return Polygon(p1, p2, p3)
        pass
    
    
    def plot_polygon(self, polygon,
                           figsize = (10,6),
                           title = None,
                           use_cache = True
                           ):

        self.cacheUtil = CacheUtil(use_cache = use_cache, verbose = self.verbose)
        
        cache_file_path, exists_cached_file = self.cacheUtil.get_cached_path(
                self.__class__, inspect.stack()[0][3],
                polygon,
                figsize,
                title,
                file_prefix = f"{self.__class__.__name__}_{inspect.stack()[0][3]}_"
                )
        
        if use_cache and exists_cached_file:
            return self.cacheUtil.load_file(cache_file_path)

        plt.ioff()
        
        plotter = Plotter2D()
        fig, ax = plotter.plot_polygon(polygon, 
                                 aspect = 'equal',
                                 color =  'green',
                                 opacity = PolygonHelper._MAIN_OPACITY
                                 )
            
        svgHelper = SvgHelper()
        svg_str = svgHelper.plt_to_svg()
    
        if not svg_str:
            if self.verbose:
                print(f"Error: svg_str could not be initialized")
            return None
            
        self.cacheUtil.save_file(svg_str, cache_file_path)
        
        plt.clf()
        plt.close()
        
        return svg_str
        pass


    pass
#class PolygonHelper:
