package de.siphalor.was.visual.jfx.controller;

import de.siphalor.was.WhatAStorage;
import de.siphalor.was.content.lang.I18n;
import de.siphalor.was.game.Balance;
import de.siphalor.was.util.Pair;
import de.siphalor.was.visual.jfx.util.BalanceEntry;
import javafx.collections.ObservableList;
import javafx.scene.chart.LineChart;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Label;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;

public class BalanceController {
	public Label totalIncomeLabel;
	public Label totalLossLabel;
	public TableView<BalanceEntry> balanceHistoryTable;
	public LineChart<NumberAxis, NumberAxis> budgetChart;
	public XYChart.Series<Integer, Integer> budgetChartSeries = new XYChart.Series<>();

	public BalanceController() {
		budgetChartSeries.setName(I18n.getInstance().getString("game.balance.chart.line"));
	}

	public void init() {
		Balance balance = WhatAStorage.getInstance().getBalance();

		ObservableList<TableColumn<BalanceEntry, ?>> columns = balanceHistoryTable.getColumns();
		columns.get(0).setCellValueFactory(new PropertyValueFactory<>("index"));
		columns.get(1).setCellValueFactory(new PropertyValueFactory<>("change"));
		columns.get(2).setCellValueFactory(new PropertyValueFactory<>("description"));

		//noinspection unchecked
		budgetChart.getData().add((XYChart.Series<NumberAxis, NumberAxis>)(Object) budgetChartSeries);
		ObservableList<XYChart.Data<Integer, Integer>> chartItems = budgetChartSeries.getData();
		chartItems.add(new XYChart.Data<>(0, 0));

		ObservableList<BalanceEntry> tableItems = balanceHistoryTable.getItems();

		I18n i18n = I18n.getInstance();

		int i = 1;
		int budget = 0;

		for (Pair<Balance.Transaction, Integer> entry : balance.getHistory()) {
			budget += entry.getSecond();

			tableItems.add(new BalanceEntry(i, entry.getSecond(), i18n.getString(entry.getFirst().getTranslationKey())));

			chartItems.add(new XYChart.Data<>(i, budget));
			i++;
		}
	}

	public void onBalanceChanged(int budget, Balance.Transaction transaction, int change, int totalIncome, int totalLoss) {
		I18n i18n = I18n.getInstance();

		totalIncomeLabel.setText(i18n.format("game.balance.total-income", totalIncome));
		totalLossLabel.setText(i18n.format("game.balance.total-loss", totalLoss));

		if (transaction != Balance.Transaction.NOOP) {
			ObservableList<BalanceEntry> items = balanceHistoryTable.getItems();
			items.add(new BalanceEntry(items.size(), change, i18n.getString(transaction.getTranslationKey())));
			balanceHistoryTable.sort();
		}

		ObservableList<XYChart.Data<Integer, Integer>> data = budgetChartSeries.getData();

		data.add(new XYChart.Data<>(data.size(), budget));
	}
}
