"""
    This file is part of mss.

    :copyright: Copyright 2021 by the mss team, see AUTHORS.
    :license: APACHE-2.0, see LICENSE for details.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
"""

import logging
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.axes_grid1.inset_locator
import matplotlib.colors
import mpl_toolkits.basemap
from matplotlib import patheffects
from mslib.mswms.mpl_hsec import MPLBasemapHorizontalSectionStyle
from mslib.mswms.utils import Targets, get_style_parameters, get_cbar_label_format, make_cbar_labels_readable
from mslib.utils import thermolib
from mslib.utils.units import convert_to

class HS_ThermalTropoStyle_SFC_01(MPLBasemapHorizontalSectionStyle):
    """
    Dynamical (2PVU) Tropopause Fields
    Dynamical tropopause plots (2-PVU level). Three styles are available:
    Pressure, potential temperature, and geopotential height.
    """
    name = "ThermalTropo01"
    title = "Thermal Tropopause"

    # Variables with the highest number of dimensions first (otherwise
    # MFDatasetCommonDims will throw an exception)!
    required_datafields = [
        ("sfc", "tropopause_altitude", "km"),
        ("sfc", "secondary_tropopause_altitude", "km"),
    ]

    styles = [
        ("default", "Overview"),
        ("primary", "Primary Thermal Tropopause"),
        ("secondary", "Secondary Thermal Tropopause"),
    ]

    def _plot_style(self):
        """
        """
        bm = self.bm
        ax = self.bm.ax
        data = self.data

        # Define colourbars and contour levels for the three styles. For
        # pressure and height, a terrain colourmap is used (bluish colours for
        # low altitudes, brownish colours for high altitudes). For potential
        # temperature, a rainbow colourmap is used (blue=low temps, red=hight
        # temps).
        fcmap = plt.cm.terrain

        if self.style == "default":
            vardata = data["tropopause_altitude"]
            label = "Primary Tropopause (km)"
        elif self.style == "primary":
            vardata = data["tropopause_altitude"]
            label = "Primary Tropopause (km)"
        elif self.style == "secondary":
            vardata = data["secondary_tropopause_altitude"]
            label = "Secondary Tropopause (km)"
        filled_contours = np.arange(5, 18, 0.25)
        thin_contours = np.arange(5, 18, 1.0)

        # Filled contour plot of pressure/geop./pot.temp. Extend the colourbar
        # to fill regions whose values exceed the colourbar range.
        contours = bm.contourf(self.lonmesh, self.latmesh, vardata,
                               filled_contours, cmap=fcmap, extend="both")

        data["secondary_tropopause_altitude"] = np.ma.masked_invalid(data["secondary_tropopause_altitude"])

        if self.style == "default":
            mask = ~data["secondary_tropopause_altitude"].mask
            bm.contourf(self.lonmesh, self.latmesh, mask, [0, 0.5, 1.5], hatches=["", "xx"], alpha=0)

        self.add_colorbar(contours, label)

        # Colors in python2.6/site-packages/matplotlib/colors.py
        cs = bm.contour(self.lonmesh, self.latmesh, vardata,
                        thin_contours, colors="yellow",
                        linewidths=0.5, linestyles="solid")
        if cs.levels[0] in thin_contours[::2]:
            lablevels = cs.levels[::2]
        else:
            lablevels = cs.levels[1::2]
        ax.clabel(cs, lablevels, colors="red", fontsize=11, fmt='%i')
