'''
Created on 17-Jun-2021

@author: bthakur
'''
from xv.util import listAttr, locatePath
import pathlib
import csv
from latex2sympy2 import latex2sympy, latex2latex
from sympy import sympify, Eq, latex
from xv.util.local import FileSystemManager
import random

from xv.util import UtilClass

class Formula(UtilClass):
    _VALUE_SEPARATOR = ','
    
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        
        self.type_of_formula = kwargs.get('type_of_formula', None)
        
        self.categories = self._str_to_list(
                        kwargs.get('categories', []))
        
        self.links = self._str_to_list(
                        kwargs.get('links', []))
        
        self.description = kwargs.get('description', None)
        self.latex_expr = kwargs.get('latex_expr', None)
        self.expr_lhs = kwargs.get('expr_lhs', None)
        self.expr_rhs = kwargs.get('expr_rhs', None)
        self.eq = self._init_eq()
        pass
    
    def _str_to_list(self, str_val):
        if str_val is None:
            return []
        
        if not isinstance(str_val, str):
            return str_val
        
        if not str_val.strip():
            return []
        
        list_vals = str_val.split(Formula._VALUE_SEPARATOR)
        list_vals = [item.strip() for item in list_vals
                      if item.strip()
                      ]
        
        return list_vals
        pass
    
        

    def _init_eq(self):
        if (self.expr_lhs is None or 
            self.expr_rhs is None):
            return None
        try:
            lhs = sympify(self.expr_lhs, evaluate = False)
            rhs = sympify(self.expr_rhs, evaluate = False)
            return Eq(lhs, rhs, evaluate = False)
        except Exception as e:
            
            sError = f"""_init_eq: {e}
            description = {self.description}
            expr_lhs = {self.expr_lhs}
            expr_rhs = {self.expr_rhs}
            """
            #print(sError)
        return None
        pass
    
    def get_latex_expr(self, expr_type = 'rhs'):
        '''
        expr_type = 'lhs' or 'rhs', 'eq', 'latex_expr'
            'latex_expr' is default value
        '''
        if expr_type == 'lhs':
            return self.latex_expr.split("=")[0] 
            
        if expr_type == 'rhs':
            return self.latex_expr.split("=")[-1] 
            
        if expr_type == 'eq':
            if not self.eq is None:
                return f"{latex(self.eq)}"

            return self.latex_expr

        return self.latex_expr
        pass
    
    def to_csv(self):
        s = []
        s.append(str(self.type_of_formula))
        s.append(str(self.expr_lhs))
        s.append(str(self.expr_rhs))
        s.append(str(self.latex_expr))
        s.append(str(self.description))
        s.append(",".join(self.categories))
        return s
        pass

    def has_category(self, search, partial_match = True):
        if not (isinstance(search, list) or isinstance(search, tuple)):
            search = [search]
            pass
        
        for item in search:
            if partial_match:
                for category in self.categories:
                    if item in category:
                        return True
                        pass
                    pass
                else:
                    if item in self.categories:
                        return True
                    pass
            pass
        return False
        pass

    def get_links_html(self):
        if self.links is None:
            return ""
        
        if len(self.links) < 1:
            return ""
        
        links_html = []
        for link in self.links:
            link_html = f"""
            <a target="_blank" href="{link}">{link}</a>
            """
            links_html.append(link_html.strip())
            
        links_html_str = "<b>Links:</b><br/><ul><li>" + "</li><li>".join(links_html) + "</li></ul>"
        return links_html_str
        pass
    
    def __str__(self):
        s = ""
        s = s + "\n" + f"""type = {self.type_of_formula}"""
        s = s + "\n" + f"""categories = {self.categories}"""
        s = s + "\n" + f"""description = {self.description}"""
        s = s + "\n" + f"""latex_expr = ${self.latex_expr}$"""
        if not self.eq is None:
            s = s + "\n" + f"""eq = ${latex(self.eq)}$"""
        else:
            if not self.expr_lhs is None:
                s = s + "\n" + f"""expr_lhs = {self.expr_lhs}"""
            if not self.expr_rhs is None:
                s = s + "\n" + f"""expr_rhs = {self.expr_rhs}"""
        return s
        pass

    def _repr_html_(self):
        return self.__str__().replace("\n", "<br />")
        pass

    def __repr__(self): 
        return self._repr_html_()

        
    pass
#class Formula:
