'''
Created on 20-Jan-2022

@author: bthakur
'''

import codecs
import inspect
import traceback
import random
import numpy as np
import pandas as pd
from sympy import (latex, Symbol, symbols,
                   Matrix,
                    Rational,
                    sin, cos, tan,
                    asin, acos, atan,
                    sinh, cosh, tanh,
                    log, exp, sqrt,
                   diff, factor,
                   Function, Eq,
                   Add,
                   simplify, solve, factorial,
                   UnevaluatedExpr as ueval
                   )

from sympy.core.numbers import One, Integer
from sympy.series import series

from xv.km.util import latex_fraction


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

import matplotlib.pyplot as plt
from xv.util import CategorizedSampleData, list_to_str

# _linear_equations_helper
# LinearEquationsHelper

class LinearEquationsHelper:

    def __init__(self, **kwargs):
        self.verbose = kwargs.get('verbose', False)
        pass

    def get_foundation_to_concept_of_matrix(self, restraurent_count = None):
        line_break = "##-##"
        human_count = random.randint(2, 4)
        friend_names = CategorizedSampleData.get_human_names()
        friend_names = random.sample(friend_names, human_count)

        food_count = random.randint(2, 4)
        food_names = CategorizedSampleData.get_food_names()
        food_names = random.sample(food_names, food_count)

        if restraurent_count is None:
            restraurent_count =  random.randint(1, 4)

        if restraurent_count == 1:
            restraurent_names = ["Shop"]
            price_cols = ["price"]
            cost_cols = ["cost"]
        else:
            restraurent_names = [f"Shop{i+1}" for i in range(restraurent_count)]
            price_cols = [f"{x}{line_break}price" for x in restraurent_names]
            cost_cols = [f"{x}{line_break}cost" for x in restraurent_names]


        qty_arr = np.random.randint(0, high=5, size=(human_count, food_count), dtype=int)
        price_arr = np.random.randint(1, high=10, size=(food_count, restraurent_count), dtype=int)


        A = Matrix(qty_arr)
        Adf = pd.DataFrame(qty_arr, columns = food_names)
        Adf['friends'] = friend_names
        Adf = Adf.set_index('friends')

        B = Matrix(price_arr)
        Bdf = pd.DataFrame(price_arr, columns = price_cols)
        Bdf['items'] = food_names
        Bdf = Bdf.set_index('items')

        cost_arr = []
        cost_arr_latex = []
        for friend_idx in range(A.shape[0]):
            shop_cost = []
            shop_cost_latex = []
            for shop_idx in range(B.T.shape[0]):
                f_s_cost = 0
                f_s_cost_latex = []
                for item_ix in range(A.shape[1]):
                    q = A[friend_idx, item_ix]
                    p = B.T[shop_idx, item_ix]
                    f_s_cost = f_s_cost + q * p
                    f_s_cost_latex.append(f"{latex(q)} * {latex(p)}")
                    pass
                f_s_cost_latex = " + ".join(f_s_cost_latex)
                shop_cost.append(f_s_cost)
                shop_cost_latex.append(f_s_cost_latex)
                pass
            cost_arr.append(shop_cost)
            cost_arr_latex.append(shop_cost_latex)
            pass


        Cdf_latex = pd.DataFrame(cost_arr_latex, columns = cost_cols)
        Cdf_latex['friends'] = friend_names
        Cdf_latex = Cdf_latex.set_index('friends')

        C = Matrix(cost_arr)
        Cdf = pd.DataFrame(cost_arr, columns = cost_cols)
        Cdf['friends'] = friend_names
        Cdf = Cdf.set_index('friends')



        friend_names_str = list_to_str(friend_names, last_sep = 'and')
        food_names_str = list_to_str(food_names, last_sep = 'and')

        qas = []
        idx_friend = random.randint(0, C.shape[0] - 1)
        qa = [f'What is the cost {friend_names[idx_friend]} pays?', C[idx_friend]]
        qas.append(qa)



        q_str = [f"{i+1}. {x[0]}" for i, x in enumerate(qas)]
        qa_str = [f"{i+1}. {x[0]}<br/>\t{x[1]}" for i, x in enumerate(qas)]

        q_str = "<br/>".join(q_str)
        qa_str = "<br/><br/>".join(qa_str)


        result = {
            'human_count': human_count,
            'friend_names': friend_names,
            'friend_names_str': friend_names_str,
            'food_count': food_count,
            'food_names': food_names,
            'food_names_str': food_names_str,
            'A': A,
            'B': B,
            'C': C,
            'Adf': Adf,
            'Bdf': Bdf,
            'Cdf': Cdf,
            'Cdf_latex': Cdf_latex,
            'qas': qas,
            'q_str': q_str,
            'qa_str': qa_str,
            'line_break': line_break,
            }
        return result
        pass


    pass
#class LinearEquationsHelper:
