1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use std::{collections::BTreeMap, path::PathBuf};

use ::error::Context;
use pyo3::{
    exceptions::{PyIndexError, PyKeyError, PyReferenceError, PyRuntimeError, PyTypeError},
    prelude::*,
    types::{PyInt, PyList},
};
use rs3cache_backend::{error, index, path::CachePath};

use crate::{
    cli::Config,
    definitions::{
        mapsquares::{MapSquare, MapSquareIterator, MapSquares},
        tiles::Tile,
    },
};

/// Container of [`PyMapSquare`]s.
/// Accessible with `from rs3cache import MapSquares`.
/// # Example
/// ```python
/// from rs3cache import *
///
/// mapsquares = MapSquares()
///```
#[pyclass(name = "MapSquares")]
pub struct PyMapSquares {
    mapsquares: Option<MapSquares>,
}

#[pymethods]
impl PyMapSquares {
    #[new]
    #[pyo3(signature=(path=None))]
    fn new(path: Option<PathBuf>) -> PyResult<Self> {
        let mut config = Config::env();
        if let Some(path) = path {
            config.input = CachePath::Argument(path.into())
        }
        Ok(Self {
            mapsquares: Some(MapSquares::new(&config)?),
        })
    }

    /// Get a specific mapsquare.
    ///
    /// # Exceptions
    /// Raises `TypeError` if `i` and `j` are not integers.
    /// Raises `IndexError` if not(0 <= i <= 100 and 0 <= j <= 200)
    /// Raises `ValueError` if there is not a mapsquare at i, j.
    ///
    /// # Example
    /// ```python
    /// from rs3cache import MapSquares
    ///
    /// mapsquares = MapSquares()
    /// lumbridge = mapsquares.get(50, 50)
    ///```
    #[pyo3(text_signature = "($self, i, j)")]
    pub fn get(&self, i: &PyAny, j: &PyAny) -> PyResult<PyMapSquare> {
        let i = i
            .downcast::<PyInt>()
            .map_err(|_| PyTypeError::new_err(format!("i was of type {}. i must be an integer.", i.get_type())))?
            .extract::<u8>()
            .map_err(|_| PyIndexError::new_err(format!("i was {i}. It must satisfy 0 <= i <= 100.")))?;
        let j = j
            .downcast::<PyInt>()
            .map_err(|_| PyTypeError::new_err(format!("j was of type {}. j must be an integer.", j.get_type())))?
            .extract::<u8>()
            .map_err(|_| PyIndexError::new_err(format!("j was {j}. It must satisfy 0 <= j <= 200.")))?;

        if i >= 100 {
            Err(PyIndexError::new_err(format!("i was {i}. It must satisfy 0 <= i <= 100.")))
        } else if j >= 200 {
            Err(PyIndexError::new_err(format!("j was {j}. It must satisfy 0 <= j <= 200.")))
        } else {
            let sq = self
                .mapsquares
                .as_ref()
                .ok_or_else(|| PyReferenceError::new_err("Mapsquares is not available after using `iter()`"))?
                .get(i, j)?;

            Ok(PyMapSquare { inner: sq })
        }
    }

    fn __iter__(&mut self, py: Python) -> PyResult<Py<PyMapSquaresIter>> {
        let inner = std::mem::take(&mut self.mapsquares);
        let inner = inner.ok_or_else(|| PyReferenceError::new_err("Mapsquares is not available after using `iter()`"))?;
        let inner = inner.into_iter();

        let iter = PyMapSquaresIter { inner };
        Py::new(py, iter)
    }
}

/// Iterator over all archives in an Index.
#[pyclass(name = "MapSquaresIter")]
pub struct PyMapSquaresIter {
    inner: MapSquareIterator,
}

#[pymethods]
impl PyMapSquaresIter {
    fn __iter__(slf: PyRef<Self>) -> PyRef<Self> {
        slf
    }

    fn __next__(&mut self, py: Python) -> Option<PyMapSquare> {
        match self.inner.next() {
            Some(Ok(sq)) => Some(PyMapSquare { inner: sq }),
            Some(Err(e)) => {
                PyRuntimeError::new_err(format!("Error: {e}")).restore(py);
                None
            }
            None => None,
        }
    }
}

/// Obtained from [`PyMapSquares`]'s [`get`](PyMapSquares::get) method.
#[pyclass(name = "MapSquare")]
pub struct PyMapSquare {
    inner: MapSquare,
}

#[pymethods]
impl PyMapSquare {
    /// The horizontal [`MapSquare`] coordinate.
    ///
    /// It can have any value in the range `0..=100`.
    #[getter]
    pub fn i(&self) -> u8 {
        self.inner.i()
    }

    /// The vertical [`MapSquare`] coordinate.
    ///
    /// It can have any value in the range `0..=200`.
    #[getter]
    pub fn j(&self) -> u8 {
        self.inner.j()
    }

    /// The [`Location`]s in a mapsquare.
    pub fn locations<'gil>(&self, py: Python<'gil>) -> PyResult<&'gil PyList> {
        let locations = self.inner.locations();

        #[cfg(feature = "rs3")]
        let locations = locations
            .context(index::FileMissing {
                index_id: 5,
                archive_id: (self.i() as u32) | (self.j() as u32) << 7,
                file: crate::definitions::indextype::MapFileType::LOCATIONS,
            })
            .context(error::Integrity)?;

        #[cfg(feature = "osrs")]
        let locations = if self.inner.xtea.is_some() {
            locations
                .context(index::ArchiveMissingNamed {
                    index_id: 5,
                    name: format!("{}{}_{}", crate::definitions::indextype::MapFileType::LOCATIONS, self.i(), self.j()),
                })
                .context(error::Integrity)?
        } else {
            locations.ok_or(rs3cache_backend::error::CacheError::Xtea { i: self.i(), j: self.j() })?
        };

        #[cfg(feature = "legacy")]
        let locations = locations
            .context(index::ArchiveMissingNamed {
                index_id: 5,
                name: format!("{}{}_{}", crate::definitions::indextype::MapFileType::LOCATIONS, self.i(), self.j()),
            })
            .context(error::Integrity)?;

        Ok(PyList::new(py, locations.iter().copied()))
    }

    /// The water [`Location`]s in a mapsquare.
    #[cfg(feature = "rs3")]
    pub fn water_locations<'gil>(&self, py: Python<'gil>) -> PyResult<&'gil PyList> {
        let water_locations = self
            .inner
            .water_locations()
            .context(index::FileMissing {
                index_id: 5,
                archive_id: (self.i() as u32) | (self.j() as u32) << 7,
                file: crate::definitions::indextype::MapFileType::WATER_LOCATIONS,
            })
            .context(error::Integrity)?;
        let water_locations = match water_locations {
            Ok(v) => v,
            Err(e) => return Err(e.into()),
        };
        Ok(PyList::new(py, water_locations.iter().copied()))
    }

    /// The [`Tile`]s in a mapsquare.   
    pub fn tiles(&self) -> PyResult<BTreeMap<(u8, u8, u8), Tile>> {
        let tiles = self.inner.tiles().ok_or_else(|| PyKeyError::new_err("not present"))?;
        let map: BTreeMap<(u8, u8, u8), Tile> = tiles.indexed_iter().map(|((p, x, y), &t)| ((p as u8, x as u8, y as u8), t)).collect();
        Ok(map)
    }

    fn __repr__(&self) -> String {
        format!("MapSquare({},{})", self.inner.i(), self.inner.j())
    }

    fn __str__(&self) -> String {
        format!("MapSquare({},{})", self.inner.i(), self.inner.j())
    }
}