'''
Created on 01-Apr-2021
@author: rishi_priyansh
'''

import random
import inspect
import traceback
from sympy import (symbols, Symbol)

from xv.km.util import latex_fraction, latex_atom
from .....helper import BaseHelper

from xv.km.managers import BaseManager
from xv.km.kelements import KProblemTemplate
        
class PhaseTransformationsManager(BaseManager):
    '''
    PhaseTransformationsManager
    Example:
        ke = PhaseTransformationsManager()
        ke.getRandomProblem()
        ke.getRandomProblem(problem_type = 0)
        ...
        
        ke.printProblem()
        ke.printAnswer()
        ke.printSolution()
        
        ke.printProblemTypes()
        
    '''    
    _OPR_TYPE_COUNT = 10
    
    def __new__(cls, *args, **kwargs):
        instance = super(PhaseTransformationsManager, cls).__new__(cls, *args, **kwargs)
        for base_class in PhaseTransformationsManager.__bases__:
            base_class.__init__(instance, *args, **kwargs)
        return instance
    
    def __init__(self, *args, **kwargs):
        pass



    def _init_problem_types(self, *args, **kwargs):
        self._append_problem_types([
            '_problem_2_185',
            '_problem_2_186',
            '_problem_2_187',
            '_problem_2_188',
            '_problem_2_189',
            '_problem_2_190',
            '_problem_2_191',
            '_problem_2_192',
            '_problem_2_193',
            '_problem_2_194',
            ])
        pass
            
    
    def _problem_2_185(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.185. A saturated water vapour is contained in a cylindrical
        vessel under a weightless piston at a temperature t = $100^{{\circ}}C$. As
        a result of a slow introduction of the piston a small fraction of the
        vapour $\Delta$m = 0.70 g gets condensed. What amount of work was
        performed over the gas? The vapour is assumed to be ideal, the
        volume of the liquid is to be neglected.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.185 The condensation takes place at constant pressure and tempcrature and the work done is
        $$
        p \Delta V
        $$
        where $\Delta V$ is the volume of the condensed vapour in the vapour phase. It is
        $$
        p \Delta V=\frac{{\Delta m}}{{M}} R T=120 \cdot 6 \mathrm{{~J}}
        $$
        where $M=18 \mathrm{{gm}}$ is the molecular weight of water.

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_186(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.186. A vessel of volume V = 6.0 l contains water together with
        its saturated vapour under a pressure of 40 atm and at a temperature
        of $250^\circ$C. The specific volume of the vapour is equal to $V_{{v}}^{{\prime}}$ = 50 l/kg
        under these conditions. The total mass of the system water-vapour
        equals m = 5.0 kg. Find the mass and the volume of the vapour. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.186 The specific volume of water (the liquid) will be written as $V_{{l}}^{{\prime}}$. Since $V_{{v}}^{{\prime}}>>V_{{l}}^{{\prime}}$, most of the weight is due to water. Thus if $m_{{l}}$ is mass of the liquid and $m_{{v}}$ that of the vapour then
        $$
        \begin{{gathered}}
        m=m_{{l}}+m_{{v}} \\
        V=m_{{l}} V_{{l}}^{{\prime}}+m_{{v}} V_{{v}}^{{\prime}} \quad \text {{ or }} \quad V-m V_{{l}}^{{\prime}}=m_{{v}}\left(V_{{v}}^{{\prime}}-V_{{l}}^{{\prime}}\right)
        \end{{gathered}}
        $$
        So $m_{{v}}=\frac{{V-m V_{{l}}^{{\prime}}}}{{V_{{v}}^{{\prime}}-V_{{1}}^{{\prime}}}}=20 \mathrm{{gm}}$ in the present case. Its volume is $m_{{\nu}} V_{{v}}^{{\prime}}=1.01$

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_187(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.187. The saturated water vapour is enclosed in a cylinder under
        a piston and occupies a volume $V_0$ = 5.0 l at the temperature t
        = $100^\circ$C. Find the mass of the liquid phase formed after the volume
        under the piston decreased isothermally to V = 1.6 l. The saturated
        vapour is assumed to be ideal.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.187 The volume of the condensed vapour was originally $V_{{0}}-V$ at temperature $T=373 \mathrm{{~K}}$. Its mass will be given by
        $p\left(V_{{0}}-V\right)=\frac{{m}}{{M}} R T$ or $m=\frac{{M p\left(V_{{0}}-V\right)}}{{R T}}=2 \mathrm{{gm}}$ where $p=$ atmospheric pressure


        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_188(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.188. A volume occupied by a saturated vapour is reduced 
        isothermally n-fold. Find what fraction ri of the final volume is occupied
        by the liquid phase if the specific volumes of the saturated vapour
        and the liquid phase differ by N times (N > n).  Solve the same
        problem under the condition that the final volume of the substance
        corresponds to the midpoint of a horizontal portion of the isothermal
        line in the diagram p, V. 

        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        $2.188$ We let $V_{{l}}=$ specific volume of liquid. $V_{{v}}^{{\prime}}=N V_{{l}}^{{\prime}}=$ specific volume of vapour. Let $V=$ Original volume of the vapour. Then
        $$
        M \frac{{p V}}{{R T}}=m_{{l}}+m_{{v}}=\frac{{V}}{{N V_{{l}}^{{\prime}}}} \text {{ or }} \frac{{V}}{{n}}=\left(m_{{l}}+N m_{{\nu}}\right) V_{{l}}^{{\prime}}
        $$
        So 
        $$
        \quad(N-1) m_{{l}} V_{{l}}^{{\prime}}=V\left(1-\frac{{1}}{{n}}\right)=\frac{{V}}{{n}}(n-1) \quad \text{{or}} \quad\eta=\frac{{m_{{l}} V_{{l}}^{{\prime}}}}{{V / n}}=\frac{{n-1}}{{N-1}}
        $$
        In the case when the final volume of the substance corresponds to the midpoint of a horizontal portion of the isothermal line in the $p, v$ diagram, the final volume must be $(1+N) \frac{{V_{{l}}^{{\prime}}}}{{2}}$ per unit mass of the substance. Of this the volume of the liquid is $V_{{1}}^{{\prime}} / 2$ per unit total mass of the substance.
        Thus
        $$
        \eta=\frac{{1}}{{1+N}}
        $$

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_189(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.189. An amount of water of mass m = 1.00 kg, boiling at standard atmospheric pressure, turns completely into saturated vapour.
        Assuming the saturated vapour to be an ideal gas find the increment
        of entropy and internal energy of the system. 

        
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.189 From the first law of thermodynamics
        $$
        \Delta U+A=Q=m q
        $$
        where $q$ is the specific latent heat of vaporization
        Now
        $$
        A=p\left(V_{{v}}-V_{{l}}\right) m=m \frac{{R T}}{{M}}
        $$
        Thus
        $$
        \Delta U=m\left(q-\frac{{R T}}{{M}}\right)
        $$
        For water this gives $\approx 2.08 \times 10^{{6}}$ Joules.

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_190(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.190. Water of mass m = 20 g is enclosed in a thermally insulated cylinder at the temperature of $0^\circ C$ under a weightless piston
        whose area is S = 410 $cm^2$. The outside pressure is equal to
        standard atmospheric pressure. To what height will the piston
        rise when the water absorbs Q = 20.0 kJ of heat?
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        $2.190$ Some of the heat used in heating water to the boiling temperature 
        $$
        \begin{{gathered}}
        T=100^{{\circ}} \mathrm{{C}}=373 \mathrm{{~K}} \quad\text{{The remaining heat}} \\
        =Q-m c \Delta T
        \end{{gathered}}
        $$
        ( $c=$ specific heat of water, $\Delta T=100 K$ ) is used to create vapour. If the piston rises to a height $h$ then the volume of vapour will be $\approx \operatorname{{sh}}($ neglecting water). Its mass will be $\frac{{p_{{0}} s h}}{{R T}} \times M$ and heat of vapourization will be $\frac{{p_{{0}} s h M q}}{{R T}}$. To this must be added the work done in creating the saturated vapour $\approx p_{{0}} s h$. Thus
        $$
        Q-m c \Delta T \approx p_{{0}} S h\left(1+\frac{{q M}}{{R T}}\right) \text {{ or }} h=\frac{{Q-m c \Delta T}}{{p_{{0}} s\left(1+\frac{{q M}}{{R T}}\right)}}=20 \mathrm{{~cm}}
        $$
                                    
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_191(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.191. One gram of saturated water vapour is enclosed in a thermally insulated 
        cylinder under a weightless piston. The outside pressure being standard, m = 1.0 g
        of water is introduced into the cylinder at a temperature to = $22^\circ $C. Neglecting the heat capacity of
        the cylinder and the friction of the piston against the cylinder's
        walls, find the work performed by the force of the atmospheric pressure during the lowering of the piston. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.191 A quantity $\frac{{m c\left(T-T_{{0}}\right)}}{{q}}$ of saturated vapour must condense to heat the water to boiling point $T=373^{{\circ}} \mathrm{{K}}$
        (Here $c=$ specific heat of water, $T_{{0}}=295 \mathrm{{~K}}=$ initial water temperature).
        The work done in lowering the piston will then be
        $$
        \frac{{m c\left(T-T_{{0}}\right)}}{{q}} \times \frac{{R T}}{{M}}=25 \mathrm{{~J}}
        $$
        since work done per unit mass of the condensed vapour is $p V=\frac{{R T}}{{M}}$
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_192(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.192. If an additional pressure $\Delta p$ of a saturated vapour over
        a convex spherical surface of a liquid is considerably less than the
        vapour pressure over a plane surface, then $\Delta p = (\rho_v / \rho_l) 2\alpha/r$, where
        $\rho_v$ and $\rho_l$ are the densities of the vapour and the liquid, a is the 
        surface tension, and r is the radius of curvature of the surface. Using
        this formula, find the diameter of water droplets at which the saturated 
        vapour pressure exceeds the vapour pressure over the plane
        surface by $\eta$ = 1.0% at a temperature t = $27^\circ$C. The vapour is
        assumed to be an ideal gas. 
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        $2.192$ Given $\Delta P=\frac{{\rho_{{\nu}}}}{{\rho_{{l}}}} \frac{{2 \alpha}}{{r}}=\frac{{\rho_{{v}}}}{{\rho_{{l}}}} \times \frac{{4 \alpha}}{{d}}=\eta p_{{\text {{vap }}}}=\eta \frac{{\frac{{m}}{{M}} R T}}{{V_{{\text {{rap }}}}}}=\frac{{\eta R T}}{{M}} \rho_{{\nu}}$
        or
        $$
        d=\frac{{4 \alpha M}}{{\rho_{{1}} R T \eta}}
        $$
        For water $\alpha=73$ dynes $/ \mathrm{{cm}}, M=18 \mathrm{{gm}}, \rho_{{l}}=\mathrm{{gm}} / \mathrm{{cc}}, T=300 \mathrm{{~K}}$, and with $\eta \sim 0.01$, we get
        $$
        d \approx 0.2 \mu \mathrm{{m}}
        $$


        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_193(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.193. Find the mass of all molecules leaving one square centimetre of water surface per second into a saturated water vapour above
        it at a temperature t = $100^\circ$C. It is assumed that $\eta$ = 3.6% of
        all water vapour molecules falling on the water surface are retained
        in the liquid phase. 

        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.193 In equilibrium the number of "liquid" molecules evaporoting must equals the number of "vapour" molecules condensing. By kinetic theory, this number is
        $$
        \eta \times \frac{{1}}{{4}} n<v>=\eta \times \frac{{1}}{{4}} n \times \sqrt{{\frac{{8}}{{\pi}} \frac{{k T}}{{m}}}}
        $$
        Its mass is
        $$
        \begin{{gathered}}
        \mu=m \times \eta \times n \times \sqrt{{\frac{{k T}}{{2 \pi m}}}}=\eta n k T \sqrt{{\frac{{m}}{{2 \pi k t}}}} \\
        =\eta p_{{0}} \sqrt{{\frac{{M}}{{2 \pi R T}}}}=0.35 \mathrm{{~g}} / \mathrm{{cm}}^{{2}} \cdot \mathrm{{s}}
        \end{{gathered}}
        $$
        where $p_{{0}}$ is atmospheric pressure and $T=373 \mathrm{{~K}}$ and $M=$ molecular weight of water.

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate

    def _problem_2_194(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = fr"""
        2.194. Find the pressure of saturated tungsten vapour at a temperature T = 2000 K if a tungsten filament is known to lose a mass
        $\mu = 1.2 \cdot 10^{{-13}} g/(s \cdot cm^2)$ from a unit area per unit time when
        evaporating into high vacuum at this temperature.
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = fr"""
        2.194 Here we must assume that $\mu$ is also the rate at which the tungsten filament loses mass when in an atmosphere of its own vapour at this temperature and that $\eta$ (of the previous problem) $\approx$ 1. Then
        $$
        p=\mu \sqrt{{\frac{{2 \pi R T}}{{M}}}}=0.9 \mathrm{{n}} \mathrm{{Pa}}
        $$
        from the previous problem where $p=$ pressure of the saturated vapour.

        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = fr"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate


    def _sample(self, *args, **kwargs):
        problemTemplate = KProblemTemplate()
        problemTemplate.problem_type = kwargs.get('problem_type')

        problem_s = f"""
        """
        problemTemplate.add_problem(problem_s.strip(), 'text/html')
        
        soln_s = f"""
        """
        problemTemplate.add_solution(soln_s.strip(), 'text/html')
        
        answer_s = f"""
        """
        problemTemplate.add_answer(answer_s.strip(), 'text/html')
        
        return problemTemplate
    
    #https://courses.lumenlearning.com/austincc-physics2/chapter/31-4-nuclear-decay-and-conservation-laws/
    
    