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
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2021-2022 Parity Technologies (UK) Ltd.
//
// 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 <https://www.gnu.org/licenses/>.

#![allow(clippy::format_in_format_args)]

use std::{
	fs,
	io::{self, Read},
	path::PathBuf,
};

use serde::de::DeserializeOwned;
use serde_json::Deserializer;
// Substrate
use sp_runtime::traits::Block as BlockT;

use super::{DbValue, Operation};

pub fn maybe_deserialize_value<B: BlockT>(
	operation: &Operation,
	value: Option<&PathBuf>,
) -> sc_cli::Result<Option<DbValue<B::Hash>>> {
	fn parse_db_values<H: DeserializeOwned, I: Read + Send>(
		input: I,
	) -> sc_cli::Result<Option<DbValue<H>>> {
		let mut stream_deser = Deserializer::from_reader(input).into_iter::<DbValue<H>>();
		if let Some(Ok(value)) = stream_deser.next() {
			Ok(Some(value))
		} else {
			Err("Failed to deserialize value data".into())
		}
	}

	if let Operation::Create | Operation::Update = operation {
		match &value {
			Some(filename) => parse_db_values::<B::Hash, _>(fs::File::open(filename)?),
			None => {
				let mut buffer = String::new();
				let res = parse_db_values(io::stdin());
				let _ = io::stdin().read_line(&mut buffer);
				res
			}
		}
	} else {
		Ok(None)
	}
}

/// Messaging and prompt.
pub trait FrontierDbMessage {
	fn key_value_error<K: core::fmt::Debug, V: core::fmt::Debug>(
		&self,
		key: K,
		value: &V,
	) -> sc_cli::Error {
		format!(
			"Key `{:?}` and Value `{:?}` are not compatible with this operation",
			key, value
		)
		.into()
	}

	fn key_column_error<K: core::fmt::Debug, V: core::fmt::Debug>(
		&self,
		key: K,
		value: &V,
	) -> sc_cli::Error {
		format!(
			"Key `{:?}` and Column `{:?}` are not compatible with this operation",
			key, value
		)
		.into()
	}

	fn key_not_empty_error<K: core::fmt::Debug>(&self, key: K) -> sc_cli::Error {
		format!("Operation not allowed for non-empty Key `{:?}`", key).into()
	}

	fn one_to_many_error(&self) -> sc_cli::Error {
		"One-to-many operation not allowed".into()
	}

	#[cfg(not(test))]
	fn confirmation_prompt<K: core::fmt::Debug, V: core::fmt::Debug>(
		&self,
		operation: &Operation,
		key: K,
		existing_value: &V,
		new_value: &V,
	) -> sc_cli::Result<()> {
		println!(
			"{}",
			format!(
				r#"
			---------------------------------------------
			Operation: {:?}
			Key: {:?}
			Existing value: {:?}
			New value: {:?}
			---------------------------------------------
			Type `confirm` and press [Enter] to confirm:
		"#,
				operation, key, existing_value, new_value
			)
		);

		let mut buffer = String::new();
		io::stdin().read_line(&mut buffer)?;
		if buffer.trim() != "confirm" {
			return Err("-- Cancel exit --".into());
		}
		Ok(())
	}

	#[cfg(test)]
	fn confirmation_prompt<K: core::fmt::Debug, V: core::fmt::Debug>(
		&self,
		_operation: &Operation,
		_key: K,
		_existing_value: &V,
		_new_value: &V,
	) -> sc_cli::Result<()> {
		Ok(())
	}
}