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
// libovgu-canteen - A canteen parser module for ovgu.
//
// Copyright (C) 2017
//     Fin Christensen <christensen.fin@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

use crate::{Additive, Allergenic, Error, FromElement, Price, Symbol, Update};
use serde::{Serialize, Deserialize};
use scraper;
use std::str::FromStr;

/// A `Meal` holds the meals name, the price, several symbols, additives,
/// and allergenics.
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Meal {
    /// The name of the meal.
    pub name: String,

    /// The price of the meal.
    pub price: Price,

    /// Symbols that the meal is annotated with.
    pub symbols: Vec<Symbol>,

    /// Additives of the meal.
    pub additives: Vec<Additive>,

    /// Allergenics contained in the meal.
    pub allergenics: Vec<Allergenic>,
}

impl FromElement for Meal {
    type Err = Error;
    fn from_element(meal_node: &scraper::ElementRef) -> Result<Self, Self::Err> {
        let notes = meal_node
            .select(&ovgu_canteen_selector![notes])
            .next()
            .and_then(|node| node.text().next())
            .unwrap_or("")
            .trim()
            .split_whitespace()
            .filter(|item| !item.is_empty());

        let mut rest = vec![];
        let additives = notes
            .filter_map(|item| match Additive::from_str(item) {
                Ok(v) => Some(v),
                Err(..) => {
                    rest.push(item);
                    None
                }
            })
            .collect();

        let allergenics = rest.iter()
            .map(|item| Allergenic::from_str(item))
            .collect::<Result<Vec<Allergenic>, Error>>()?;

        let name = meal_node
            .select(&ovgu_canteen_selector![name])
            .next()
            .and_then(|node| node.text().next())
            .ok_or(Error::NotAvailable { member: "name", object: "meal" })
            .map(|n| n.trim())?;

        let price = meal_node
            .select(&ovgu_canteen_selector![price])
            .next()
            .and_then(|node| node.text().last())
            .ok_or(Error::NotAvailable { member: "price", object: "meal" })
            .and_then(|p| Price::from_str(p.trim()))?;

        let symbols = meal_node
            .select(&ovgu_canteen_selector![symbols])
            .map(|img| {
                img.value()
                    .attr("title")
                    .ok_or(Error::NotAvailable { member: "symbols", object: "meal" })
                    .and_then(|t| Symbol::from_str(t.trim()))
            })
            .collect::<Result<Vec<Symbol>, Error>>()?;

        Ok(Meal {
            name: name.to_owned(),
            price: price,
            symbols: symbols,
            additives: additives,
            allergenics: allergenics,
        })
    }
}

impl Update for Meal {
    type Err = Error;
    fn update(&mut self, from: &Self) -> Result<(), Self::Err> {
        self.price.update(&from.price)?;

        for symbol in from.symbols.iter() {
            if !self.symbols.contains(symbol) {
                self.symbols.push(symbol.clone());
            }
        }

        for additive in from.additives.iter() {
            if !self.additives.contains(additive) {
                self.additives.push(additive.clone());
            }
        }

        for allergenic in from.allergenics.iter() {
            if !self.allergenics.contains(allergenic) {
                self.allergenics.push(allergenic.clone());
            }
        }

        Ok(())
    }
}

impl PartialEq for Meal {
    fn eq(&self, other: &Self) -> bool {
        self.name == other.name
    }
}