# Path: metatlas/io/metatlas_get_data_helper_fun.py
# def get_bpc(filename,dataset='ms1_pos',integration='bpc'):
#     """
#     Gets the basepeak chromatogram for a file.
#     filename: File can be either a metatlas lcmsrun object or a full path to an hdf5file
#     dataset: ms1_pos, ms1_neg, ms2_pos, ms2_neg
# 
#     Returns:
#     A pandas dataframe with the value at the maximum intensity at each retention time
#     """
#     df_container = df_container_from_metatlas_file(filename)
#     if integration=='bpc':
#         bpc = df_container[dataset].sort_values('i', ascending=False).groupby('rt', as_index=False).first().sort_values('rt',ascending=True)
#         return bpc
#     else:
#         tic = df_container[dataset][['rt','i']].groupby('rt',as_index=False).sum().sort_values('rt',ascending=True)
#         return tic
# 
# Path: metatlas/plots/plot_set.py
# def restore_matplotlib_settings(func):
#     def wrapper(*args, **kwargs):
#     def __init__(self, title: str, group_name: str):
#     def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
#     def __init__(
#         self,
#         plots: Sequence[Plot],
#         max_plots_per_fig: int = 30,
#         x_min: Optional[float] = None,
#         x_max: Optional[float] = None,
#         y_min: Optional[float] = None,
#         y_max: Optional[float] = None,
#         sharey: bool = True,
#         font_scale: float = 2,
#     ):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, exc_tb):
#     def limit_axes(
#         self,
#         x_min: Optional[float],
#         x_max: Optional[float],
#         y_min: Optional[float],
#         y_max: Optional[float],
#     ) -> None:
#     def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None:
#     def close(self):
# def _get_xy(artist: matplotlib.artist.Artist) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
# def _autoscale(ax: matplotlib.axes.Axes, axis: str = "y", sides: str = "both", margin: float = 0.1) -> None:
# def _update_limts(
#     low: float,
#     high: float,
#     fixed: npt.NDArray[np.float64],
#     dependent: npt.NDArray[np.float64],
#     fixed_limits: Tuple[float, float],
# ) -> Tuple[float, float]:
# def _calculate_new_limit(
#     fixed: npt.NDArray[np.float64], dependent: npt.NDArray[np.float64], fixed_limits: Tuple[float, float]
# ) -> Tuple[float, float]:
# class Plot(ABC):
# class PlotSet(ABC):
# 
# Path: metatlas/plots/utils.py
# BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"]
# def colors() -> Generator:
# def subplot_dimensions(num: int) -> Tuple[int, int]:
# def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]:
# def is_in_range(a: List[float], start: float, stop: float) -> List[bool]:
# def fill_under(
#     ax: matplotlib.axes.Axes,
#     x: List[float],
#     y: List[float],
#     between: Optional[Tuple[float, float]] = None,
#     **kwargs,
# ) -> None:
# def pdf_with_text(text: str, file_name: str, size: int = 24):


import logging
import matplotlib
from pathlib import Path
from typing import Any, List, Optional
from matplotlib.ticker import MultipleLocator
from metatlas.io.metatlas_get_data_helper_fun import get_bpc
from metatlas.plots import plot_set
from metatlas.plots import utils
        """Draw plot of TIC on ax"""
        super().plot(ax, back_color)
        dataset = f"ms1_{self.polarity[:3]}"
        tic_df = get_bpc(self.h5_file_name, dataset=dataset, integration="tic")
        ax.plot(tic_df["rt"], tic_df["i"])
        ax.xaxis.set_minor_locator(MultipleLocator(1))


def save_sample_tic_pdf(
    data: MetatlasDataset,
    polarity: str,
    file_name: str,
    overwrite: bool = False,
    sharey: bool = True,
    x_min: Optional[float] = None,
    x_max: Optional[float] = None,
    y_min: Optional[float] = None,
    y_max: Optional[float] = None,
    max_plots_per_page: int = 30,
) -> None:
    """Generate a PDF of TIC plots for samples within data"""
    assert polarity in ["positive", "negative"]
    file_order_tics = []
    for sample in data:
        fields = Path(sample[0]["lcmsrun"].name).stem.split("_")
        title = f"{fields[0]}_{fields[11]}_{fields[13]}_{fields[15]}"
        group_name = sample[0]["group"].short_name
        h5_file_name = sample[0]["lcmsrun"].hdf5_file
        file_order_tics.append(Tic(title, group_name, h5_file_name, polarity))
    tics = sorted(file_order_tics, key=lambda x: (x.group_name, x.title))

# Path: metatlas/io/metatlas_get_data_helper_fun.py
# def get_bpc(filename,dataset='ms1_pos',integration='bpc'):
#     """
#     Gets the basepeak chromatogram for a file.
#     filename: File can be either a metatlas lcmsrun object or a full path to an hdf5file
#     dataset: ms1_pos, ms1_neg, ms2_pos, ms2_neg
# 
#     Returns:
#     A pandas dataframe with the value at the maximum intensity at each retention time
#     """
#     df_container = df_container_from_metatlas_file(filename)
#     if integration=='bpc':
#         bpc = df_container[dataset].sort_values('i', ascending=False).groupby('rt', as_index=False).first().sort_values('rt',ascending=True)
#         return bpc
#     else:
#         tic = df_container[dataset][['rt','i']].groupby('rt',as_index=False).sum().sort_values('rt',ascending=True)
#         return tic
# 
# Path: metatlas/plots/plot_set.py
# def restore_matplotlib_settings(func):
#     def wrapper(*args, **kwargs):
#     def __init__(self, title: str, group_name: str):
#     def plot(self, ax: matplotlib.axes.Axes, back_color: utils.Color = "white") -> None:
#     def __init__(
#         self,
#         plots: Sequence[Plot],
#         max_plots_per_fig: int = 30,
#         x_min: Optional[float] = None,
#         x_max: Optional[float] = None,
#         y_min: Optional[float] = None,
#         y_max: Optional[float] = None,
#         sharey: bool = True,
#         font_scale: float = 2,
#     ):
#     def __enter__(self):
#     def __exit__(self, exc_type, exc_value, exc_tb):
#     def limit_axes(
#         self,
#         x_min: Optional[float],
#         x_max: Optional[float],
#         y_min: Optional[float],
#         y_max: Optional[float],
#     ) -> None:
#     def save_pdf(self, file_name: str, title: str, overwrite: bool = False) -> None:
#     def close(self):
# def _get_xy(artist: matplotlib.artist.Artist) -> Tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]:
# def _autoscale(ax: matplotlib.axes.Axes, axis: str = "y", sides: str = "both", margin: float = 0.1) -> None:
# def _update_limts(
#     low: float,
#     high: float,
#     fixed: npt.NDArray[np.float64],
#     dependent: npt.NDArray[np.float64],
#     fixed_limits: Tuple[float, float],
# ) -> Tuple[float, float]:
# def _calculate_new_limit(
#     fixed: npt.NDArray[np.float64], dependent: npt.NDArray[np.float64], fixed_limits: Tuple[float, float]
# ) -> Tuple[float, float]:
# class Plot(ABC):
# class PlotSet(ABC):
# 
# Path: metatlas/plots/utils.py
# BACKGROUND_COLORS = ["white", "lightyellow", "whitesmoke", "lavenderblush"]
# def colors() -> Generator:
# def subplot_dimensions(num: int) -> Tuple[int, int]:
# def wrap_subplots(num: int, **kwargs) -> Tuple[matplotlib.figure.Figure, List[matplotlib.axes.Axes]]:
# def is_in_range(a: List[float], start: float, stop: float) -> List[bool]:
# def fill_under(
#     ax: matplotlib.axes.Axes,
#     x: List[float],
#     y: List[float],
#     between: Optional[Tuple[float, float]] = None,
#     **kwargs,
# ) -> None:
# def pdf_with_text(text: str, file_name: str, size: int = 24):


# Path: metatlas/plots/tic.py
import logging
import matplotlib
from pathlib import Path
from typing import Any, List, Optional
from matplotlib.ticker import MultipleLocator
from metatlas.io.metatlas_get_data_helper_fun import get_bpc
from metatlas.plots import plot_set
from metatlas.plots import utils

        """Draw plot of TIC on ax"""
        super().plot(ax, back_color)
        dataset = f"ms1_{self.polarity[:3]}"
        tic_df = get_bpc(self.h5_file_name, dataset=dataset, integration="tic")
        ax.plot(tic_df["rt"], tic_df["i"])
        ax.xaxis.set_minor_locator(MultipleLocator(1))


def save_sample_tic_pdf(
    data: MetatlasDataset,
    polarity: str,
    file_name: str,
    overwrite: bool = False,
    sharey: bool = True,
    x_min: Optional[float] = None,
    x_max: Optional[float] = None,
    y_min: Optional[float] = None,
    y_max: Optional[float] = None,
    max_plots_per_page: int = 30,
) -> None:
    """Generate a PDF of TIC plots for samples within data"""
    assert polarity in ["positive", "negative"]
    file_order_tics = []
    for sample in data:
        fields = Path(sample[0]["lcmsrun"].name).stem.split("_")
        title = f"{fields[0]}_{fields[11]}_{fields[13]}_{fields[15]}"
        group_name = sample[0]["group"].short_name
        h5_file_name = sample[0]["lcmsrun"].hdf5_file
        file_order_tics.append(Tic(title, group_name, h5_file_name, polarity))
    tics = sorted(file_order_tics, key=lambda x: (x.group_name, x.title))

    with plot_set.PlotSet(tics, max_plots_per_page, x_min, x_max, y_min, y_max, sharey) as plots: