use super::{
	parachains_origin, AccountId, AllPalletsWithSystem, Balances, Dmp, Fellows, ParaId, Runtime,
	RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, Treasury, WeightToFee, XcmPallet,
};
use crate::governance::StakingAdmin;
use frame_support::{
	parameter_types,
	traits::{Contains, Equals, Everything, Nothing},
	weights::Weight,
};
use frame_system::EnsureRoot;
use rococo_runtime_constants::{currency::CENTS, system_parachain::*};
use runtime_common::{
	xcm_sender::{ChildParachainRouter, ExponentialPrice},
	ToAuthor,
};
use sp_core::ConstU32;
use xcm::latest::prelude::*;
use xcm_builder::{
	AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
	AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative,
	ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FixedWeightBounds,
	FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain,
	IsConcrete, MintLocation, OriginToPluralityVoice, SignedAccountId32AsNative,
	SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId,
	UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
	XcmFeeManagerFromComponents, XcmFeeToAccount,
};
use xcm_executor::XcmExecutor;
parameter_types! {
	pub TokenLocation: Location = Here.into_location();
	pub RootLocation: Location = Location::here();
	pub const ThisNetwork: NetworkId = NetworkId::Rococo;
	pub UniversalLocation: InteriorLocation = ThisNetwork::get().into();
	pub CheckAccount: AccountId = XcmPallet::check_account();
	pub LocalCheckAccount: (AccountId, MintLocation) = (CheckAccount::get(), MintLocation::Local);
	pub TreasuryAccount: AccountId = Treasury::account_id();
}
pub type LocationConverter = (
	ChildParachainConvertsVia<ParaId, AccountId>,
	AccountId32Aliases<ThisNetwork, AccountId>,
	HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
);
pub type LocalAssetTransactor = FungibleAdapter<
	Balances,
	IsConcrete<TokenLocation>,
	LocationConverter,
	AccountId,
	LocalCheckAccount,
>;
type LocalOriginConverter = (
	SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
	ChildParachainAsNative<parachains_origin::Origin, RuntimeOrigin>,
	SignedAccountId32AsNative<ThisNetwork, RuntimeOrigin>,
);
parameter_types! {
	pub const BaseXcmWeight: Weight = Weight::from_parts(1_000_000_000, 64 * 1024);
	pub FeeAssetId: AssetId = AssetId(TokenLocation::get());
	pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3);
}
pub type PriceForChildParachainDelivery =
	ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, Dmp>;
pub type XcmRouter = WithUniqueTopic<
	ChildParachainRouter<Runtime, XcmPallet, PriceForChildParachainDelivery>,
>;
parameter_types! {
	pub Roc: AssetFilter = Wild(AllOf { fun: WildFungible, id: AssetId(TokenLocation::get()) });
	pub AssetHub: Location = Parachain(ASSET_HUB_ID).into_location();
	pub Contracts: Location = Parachain(CONTRACTS_ID).into_location();
	pub Encointer: Location = Parachain(ENCOINTER_ID).into_location();
	pub BridgeHub: Location = Parachain(BRIDGE_HUB_ID).into_location();
	pub People: Location = Parachain(PEOPLE_ID).into_location();
	pub Broker: Location = Parachain(BROKER_ID).into_location();
	pub Tick: Location = Parachain(100).into_location();
	pub Trick: Location = Parachain(110).into_location();
	pub Track: Location = Parachain(120).into_location();
	pub RocForTick: (AssetFilter, Location) = (Roc::get(), Tick::get());
	pub RocForTrick: (AssetFilter, Location) = (Roc::get(), Trick::get());
	pub RocForTrack: (AssetFilter, Location) = (Roc::get(), Track::get());
	pub RocForAssetHub: (AssetFilter, Location) = (Roc::get(), AssetHub::get());
	pub RocForContracts: (AssetFilter, Location) = (Roc::get(), Contracts::get());
	pub RocForEncointer: (AssetFilter, Location) = (Roc::get(), Encointer::get());
	pub RocForBridgeHub: (AssetFilter, Location) = (Roc::get(), BridgeHub::get());
	pub RocForPeople: (AssetFilter, Location) = (Roc::get(), People::get());
	pub RocForBroker: (AssetFilter, Location) = (Roc::get(), Broker::get());
	pub const MaxInstructions: u32 = 100;
	pub const MaxAssetsIntoHolding: u32 = 64;
}
pub type TrustedTeleporters = (
	xcm_builder::Case<RocForTick>,
	xcm_builder::Case<RocForTrick>,
	xcm_builder::Case<RocForTrack>,
	xcm_builder::Case<RocForAssetHub>,
	xcm_builder::Case<RocForContracts>,
	xcm_builder::Case<RocForEncointer>,
	xcm_builder::Case<RocForBridgeHub>,
	xcm_builder::Case<RocForPeople>,
	xcm_builder::Case<RocForBroker>,
);
pub struct OnlyParachains;
impl Contains<Location> for OnlyParachains {
	fn contains(loc: &Location) -> bool {
		matches!(loc.unpack(), (0, [Parachain(_)]))
	}
}
pub struct LocalPlurality;
impl Contains<Location> for LocalPlurality {
	fn contains(loc: &Location) -> bool {
		matches!(loc.unpack(), (0, [Plurality { .. }]))
	}
}
pub type Barrier = TrailingSetTopicAsId<(
	TakeWeightCredit,
	AllowKnownQueryResponses<XcmPallet>,
	WithComputedOrigin<
		(
			AllowTopLevelPaidExecutionFrom<Everything>,
			AllowExplicitUnpaidExecutionFrom<IsChildSystemParachain<ParaId>>,
			AllowSubscriptionsFrom<OnlyParachains>,
		),
		UniversalLocation,
		ConstU32<8>,
	>,
)>;
pub type WaivedLocations = (SystemParachains, Equals<RootLocation>, LocalPlurality);
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
	type RuntimeCall = RuntimeCall;
	type XcmSender = XcmRouter;
	type AssetTransactor = LocalAssetTransactor;
	type OriginConverter = LocalOriginConverter;
	type IsReserve = ();
	type IsTeleporter = TrustedTeleporters;
	type UniversalLocation = UniversalLocation;
	type Barrier = Barrier;
	type Weigher = WeightInfoBounds<
		crate::weights::xcm::RococoXcmWeight<RuntimeCall>,
		RuntimeCall,
		MaxInstructions,
	>;
	type Trader =
		UsingComponents<WeightToFee, TokenLocation, AccountId, Balances, ToAuthor<Runtime>>;
	type ResponseHandler = XcmPallet;
	type AssetTrap = XcmPallet;
	type AssetLocker = ();
	type AssetExchanger = ();
	type AssetClaims = XcmPallet;
	type SubscriptionService = XcmPallet;
	type PalletInstancesInfo = AllPalletsWithSystem;
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
	type FeeManager = XcmFeeManagerFromComponents<
		WaivedLocations,
		XcmFeeToAccount<Self::AssetTransactor, AccountId, TreasuryAccount>,
	>;
	type MessageExporter = ();
	type UniversalAliases = Nothing;
	type CallDispatcher = RuntimeCall;
	type SafeCallFilter = Everything;
	type Aliasers = Nothing;
	type TransactionalProcessor = FrameTransactionalProcessor;
}
parameter_types! {
	pub const CollectiveBodyId: BodyId = BodyId::Unit;
	pub const StakingAdminBodyId: BodyId = BodyId::Defense;
	pub const FellowsBodyId: BodyId = BodyId::Technical;
}
pub type LocalOriginToLocation = (
	SignedToAccountId32<RuntimeOrigin, AccountId, ThisNetwork>,
);
pub type StakingAdminToPlurality =
	OriginToPluralityVoice<RuntimeOrigin, StakingAdmin, StakingAdminBodyId>;
pub type FellowsToPlurality = OriginToPluralityVoice<RuntimeOrigin, Fellows, FellowsBodyId>;
pub type LocalPalletOriginToLocation = (
	StakingAdminToPlurality,
	FellowsToPlurality,
);
impl pallet_xcm::Config for Runtime {
	type RuntimeEvent = RuntimeEvent;
	type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalPalletOriginToLocation>;
	type XcmRouter = XcmRouter;
	type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
	type XcmExecuteFilter = Everything;
	type XcmExecutor = XcmExecutor<XcmConfig>;
	type XcmTeleportFilter = Everything;
	type XcmReserveTransferFilter = Everything;
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
	type UniversalLocation = UniversalLocation;
	type RuntimeOrigin = RuntimeOrigin;
	type RuntimeCall = RuntimeCall;
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
	type Currency = Balances;
	type CurrencyMatcher = IsConcrete<TokenLocation>;
	type TrustedLockers = ();
	type SovereignAccountOf = LocationConverter;
	type MaxLockers = ConstU32<8>;
	type MaxRemoteLockConsumers = ConstU32<0>;
	type RemoteLockConsumerIdentifier = ();
	type WeightInfo = crate::weights::pallet_xcm::WeightInfo<Runtime>;
	type AdminOrigin = EnsureRoot<AccountId>;
}