ygopro-data 0.1.1

Data models for the YGOPro protocol: cards, messages and replay structures.
Documentation
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! The constants and enums shared across the protocol.
//!
//! Holds the player positions (`Netplayer`, `CorePlayer`), card attributes, locations,
//! phases, and the other protocol constants.

#![allow(non_upper_case_globals)]
#![allow(non_camel_case_types)]

use binrw::BinRead;
use binrw::BinWrite;
use num_enum::IntoPrimitive;
use num_enum::TryFromPrimitive;
use num_enum::FromPrimitive;
use bitflags::bitflags;
use modular_bitfield::bitfield;
use modular_bitfield::Specifier;
use modular_bitfield::error::InvalidBitPattern;
use modular_bitfield::error::OutOfBounds;
use modular_bitfield::specifiers::B3;

use crate::data::DeckErrorType;

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u16)]
#[repr(u16)]
pub enum Network {
    ServerId = 29736,
    ClientId = 57078,
}

/// The position where a player is in a room slot.
///
/// In C++, `Netplayer` is a single enum value reused in many places. The Rust version
/// splits it into several distinct types that are no longer guaranteed to be equal. This
/// `Netplayer` is a compromise for the ygopro crate, adding the `Undecided` category and
/// the observer's index. In particular, `Observer(255)` means the observer's slot is
/// unknown.
///
/// These added parts are dropped when serializing: `Observer` always becomes `255`, to
/// match the original data protocol. So (de)serialization of this type loses information
/// and must be handled carefully, especially when using [`Complex`](crate::complex::Complex).
///
/// See also: [`CorePlayer`],
/// [`ChatSource`](crate::message::server_to_client::ChatSource).
#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, Debug, PartialOrd, Ord, Hash)]
#[br(map = |raw: u8| Netplayer::from_primitive(raw))]
#[bw(map = |value: &Netplayer| u8::from(*value))]
#[repr(u8)]
pub enum Netplayer {
    Player(u8),
    Observer(u8),
    Undecided(u8),
    Unknown
}

impl FromPrimitive for Netplayer {
    type Primitive = u8;

    fn from_primitive(number: Self::Primitive) -> Self {
        if number <= 6 { Netplayer::Player(number) }
        else if number == 7 { Netplayer::Observer(255) }
        else { Netplayer::Unknown }
    }
}

impl From<Netplayer> for u8 {
    fn from(value: Netplayer) -> Self {
        match value {
            Netplayer::Player(index) => index,
            Netplayer::Observer(_) => 7,
            Netplayer::Undecided(_) => 255,
            Netplayer::Unknown => 255,
        }
    }
}

impl Specifier for Netplayer {
    const BITS: usize = 4;
    type Bytes = u8;
    type InOut = Self;

    fn into_bytes(input: Self) -> Result<Self::Bytes, OutOfBounds> {
        let byte = u8::from(input);
        if byte >= (1 << Self::BITS) {
            return Err(OutOfBounds);
        }
        Ok(byte)
    }

    fn from_bytes(bytes: Self::Bytes) -> Result<Self, InvalidBitPattern<Self::Bytes>> {
        let netplayer = Netplayer::from_primitive(bytes);
        if netplayer == Netplayer::Unknown {
            return Err(InvalidBitPattern::new(bytes));
        }
        Ok(netplayer)
    }
}

/// The position where a player is in ygocore.
///
/// This is a new type invented by this crate. Its values are exactly the same as the
/// player in ygocore (often written as `tp` in lua). They are unrelated to the network
/// slot of the first-attack player, so `CorePlayer` is not equal to [`Netplayer`]. How to
/// relate `Netplayer` and `CorePlayer` is the downstream's own responsibility.
///
/// See also: [`Netplayer`].
#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug, PartialOrd, Ord, Hash)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum CorePlayer {
    FirstAttackPlayer = 0,
    SecondAttackPlayer = 1,
    None = 2,
    All = 3,
    /// This value is only used as `reason_player` when reason is rule.
    Rule = 5,
}

impl CorePlayer {
    pub fn opponent(&self) -> CorePlayer {
        match *self {
            CorePlayer::FirstAttackPlayer => CorePlayer::SecondAttackPlayer,
            CorePlayer::SecondAttackPlayer => CorePlayer::FirstAttackPlayer,
            CorePlayer::None => CorePlayer::None,
            CorePlayer::All => CorePlayer::All,
            CorePlayer::Rule => CorePlayer::Rule,
        }
    }
}

impl From<Netplayer> for CorePlayer {
    fn from(player: Netplayer) -> Self {
        match player {
            Netplayer::Player(u) => if u % 2 == 0 { CorePlayer::FirstAttackPlayer } else { CorePlayer::SecondAttackPlayer }
            _ => CorePlayer::None
        }
    }
}

impl From<CorePlayer> for Netplayer {
    fn from(player: CorePlayer) -> Self {
        match player {
            CorePlayer::FirstAttackPlayer => Netplayer::Player(0),
            CorePlayer::SecondAttackPlayer => Netplayer::Player(1),
            CorePlayer::None => Netplayer::Unknown,
            CorePlayer::All => Netplayer::Unknown,
            CorePlayer::Rule => Netplayer::Unknown,
        }
    }
}

impl std::ops::Mul for CorePlayer {
    type Output = CorePlayer;

    fn mul(self, rhs: Self) -> Self::Output {
        if self == rhs { return self; }
        match (self, rhs) {
            (CorePlayer::None, _) => rhs,
            (_, CorePlayer::None) => self,
            (CorePlayer::Rule, _) | (_, CorePlayer::Rule) => CorePlayer::Rule,
            (_, _) => CorePlayer::All
        }
    }
}

pub trait PlayerConverter {
    fn to_net_player(&self, core_player: CorePlayer) -> Netplayer;
    fn to_core_player(&self, net_player: Netplayer) -> CorePlayer;
}

#[bitfield]
#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, Debug)]
#[br(map = Self::from_bytes)]
#[bw(map = |&x| Self::into_bytes(x))]
#[repr(u8)]
pub struct TypeChange {
    pub player: Netplayer,
    pub host: bool,
    #[skip] __: B3,
}

#[derive(Specifier, Copy, Clone, Eq, PartialEq, Debug)]
#[bits = 4]
#[repr(u8)]
pub enum PlayerChangeState {
    Observe = 0x8,
    Ready = 0x9,
    Notready = 0xa,
    Leave = 0xb,
}

#[bitfield]
#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, Debug)]
#[br(map = Self::from_bytes)]
#[bw(map = |&x| Self::into_bytes(x))]
#[repr(u8)]
pub struct PlayerChange {
    pub state: PlayerChangeState,
    pub player: Netplayer,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr = u8)]
#[repr(u8)]
pub enum JoinError {
    RoomFull = 0,
    WrongPassword = 1,
    HostRefused = 2
}


#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum ErrorMessage {
    JoinError(JoinError) = 1,
    DeckError(crate::data::DeckError) = 2,
    SideError = 3,
    VersionError(u16) = 4,
}

fn invalid_data(error: impl std::fmt::Display + Send + Sync + 'static) -> binrw::Error {
    std::io::Error::new(std::io::ErrorKind::InvalidData, error.to_string()).into()
}

impl BinRead for ErrorMessage {
    type Args<'a> = ();

    fn read_options<R: std::io::prelude::Read + std::io::prelude::Seek>(
        reader: &mut R,
        endian: binrw::Endian,
        args: Self::Args<'_>,
    ) -> binrw::prelude::BinResult<Self> {
        let value = u32::read_options(reader, endian, args)?;
        let code = u32::read_options(reader, endian, args)?;
        let res = match value {
            1 => {
                let err_type = u8::try_from(code).map_err(invalid_data)?;
                ErrorMessage::JoinError(JoinError::try_from(err_type).map_err(|_| invalid_data("invalid JoinError"))?)
            }
            2 => ErrorMessage::DeckError(crate::data::DeckError::from_bytes(code.to_ne_bytes())),
            3 => ErrorMessage::SideError,
            4 => ErrorMessage::VersionError(u16::try_from(code).map_err(invalid_data)?),
            _ => return Err(binrw::Error::NoVariantMatch { pos: 0 }),
        };
        Ok(res)
    }
}

impl BinWrite for ErrorMessage {
    type Args<'a> = ();

    fn write_options<W: std::io::prelude::Write + std::io::prelude::Seek>(&self,
        writer: &mut W,
        endian: binrw::Endian,
        args: Self::Args<'_>,
    ) -> binrw::prelude::BinResult<()> {
        match self {
            ErrorMessage::JoinError(join_error) => {
                u32::write_options(&1, writer, endian, args)?;
                u32::write_options(&(*join_error as u8 as u32), writer, endian, args)?;
            }
            ErrorMessage::DeckError(deck_error) => {
                u32::write_options(&2, writer, endian, args)?;
                u32::write_options(&u32::from(*deck_error), writer, endian, args)?;
            },
            ErrorMessage::SideError => {
                u32::write_options(&3, writer, endian, args)?;
                u32::write_options(&0, writer, endian, args)?;
            },
            ErrorMessage::VersionError(version) => {
                u32::write_options(&4, writer, endian, args)?;
                u32::write_options(&(*version as u32), writer, endian, args)?;
            },
        }
        Ok(())
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug, Hash)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum Mode {
    Single = 0,
    Match = 1,
    Tag = 2,
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Location: u8 {
        const Limbo = 0;
        const Deck = 0x1;
        const Hand = 0x2;
        const MZone = 0x4;
        const SZone = 0x8;
        const Grave = 0x10;
        const Removed = 0x20;
        const Extra = 0x40;
        const Overlay = 0x80;
        const OnField = 0xc;
        // FZone = 0x100,
        // PZone = 0x200,
        // DeckBot = 0x10001,
        // DeckShf = 0x20001,
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Position: u8 {
        const Any = 0;
        const FaceupAttack = 0x1;
        const FaceDownAttack = 0x2;
        const FaceupDefense = 0x4;
        const FacedownDefense = 0x8;
        const Faceup = 0x5;
        const Facedown = 0xa;
        const Attack = 0x3;
        const Defense = 0xc;
        const Reveal = 0x80;
        // NoFlipEffect = 0x10000
    }
}

impl Position {
    pub fn is_face_down(&self) -> bool {
        self.intersects(Position::Facedown)
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Timing: u32 {
        const DrawPhase = 0x1;
        const StandbyPhase = 0x2;
        const MainEnd = 0x4;
        const BattleStart = 0x8;
        const BattleEnd = 0x10;
        const EndPhase = 0x20;
        const Summon = 0x40;
        const SpecialSummon = 0x80;
        const FlipSummon = 0x100;
        const MonsterSet = 0x200;
        const SpellTrapSet = 0x400;
        const PositionChange = 0x800;
        const Attack = 0x1000;
        const DamageStep = 0x2000;
        const DamageCalculate = 0x4000;
        const ChainEnd = 0x8000;
        const Draw = 0x10000;
        const Damage = 0x20000;
        const Recover = 0x40000;
        const Destroy = 0x80000;
        const Remove = 0x100000;
        const ToHand = 0x200000;
        const ToDeck = 0x400000;
        const ToGrave = 0x800000;
        const BattlePhase = 0x1000000;
        const Equip = 0x2000000;
        const BattleStepEnd = 0x4000000;
        const Battled = 0x8000000;
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Type: u32 {
        const Monster = 0x1;
        const Spell = 0x2;
        const Trap = 0x4;
        const Normal = 0x10;
        const Effect = 0x20;
        const Fusion = 0x40;
        const Ritual = 0x80;
        const Trapmonster = 0x100;
        const Spirit = 0x200;
        const Union = 0x400;
        const Dual = 0x800;
        const Tuner = 0x1000;
        const Synchro = 0x2000;
        const Token = 0x4000;
        const Quickplay = 0x10000;
        const Continuous = 0x20000;
        const Equip = 0x40000;
        const Field = 0x80000;
        const Counter = 0x100000;
        const Flip = 0x200000;
        const Toon = 0x400000;
        const Xyz = 0x800000;
        const Pendulum = 0x1000000;
        const SpecialSummon = 0x2000000;
        const Link = 0x4000000;
        const ExtraDeck = 0x4802040;
    }
}


bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Race: u32 {
        const Warrior = 0x1;
        const Spellcaster = 0x2;
        const Fairy = 0x4;
        const Fiend = 0x8;
        const Zombie = 0x10;
        const Machine = 0x20;
        const Aqua = 0x40;
        const Pyro = 0x80;
        const Rock = 0x100;
        const Windbeast = 0x200;
        const Plant = 0x400;
        const Insect = 0x800;
        const Thunder = 0x1000;
        const Dragon = 0x2000;
        const Beast = 0x4000;
        const Beastwarrior = 0x8000;
        const Dinosaur = 0x10000;
        const Fish = 0x20000;
        const Seaserpent = 0x40000;
        const Reptile = 0x80000;
        const Psycho = 0x100000;
        const Devine = 0x200000;
        const Creatorgod = 0x400000;
        const Wyrm = 0x800000;
        const Cyberse = 0x1000000;
        const Illusion = 0x2000000;
        const All = 0x3ffffff;
    }
}

impl Race {
    pub const COUNT: u8 = 26;
}


bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Reason: u32 {
        const Destroy = 0x1;
        const Release = 0x2;
        const Temporary = 0x4;
        const Material = 0x8;
        const Summon = 0x10;
        const Battle = 0x20;
        const Effect = 0x40;
        const Cost = 0x80;
        const Adjust = 0x100;
        const LostTarget = 0x200;
        const Rule = 0x400;
        const SpecialSummon = 0x800;
        const DisableSummon = 0x1000;
        const Flip = 0x2000;
        const Discard = 0x4000;
        const RecoverDamage = 0x8000;
        const RecoverRecover = 0x10000;
        const Return = 0x20000;
        const Fusion = 0x40000;
        const Synchro = 0x80000;
        const Ritual = 0x100000;
        const Xyz = 0x200000;
        const Replace = 0x1000000;
        const Draw = 0x2000000;
        const Redirect = 0x4000000;
        const Reveal = 0x8000000;
        const Link = 0x10000000;
        const LostOverlay = 0x20000000;
        const Maintenance = 0x40000000;
        const Action = 0x80000000;
        const Procedure = 0x10280000;
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Status: u32 {
        const Disabled = 0x0001;
        const ToEnable = 0x0002;
        const ToDisable = 0x0004;
        const ProcessComplete = 0x0008;
        const SetTurn = 0x0010;
        const NoLevel = 0x0020;
        const BattleResult = 0x0040;
        const SpecialSummonStep = 0x0080;
        const CannotChangeForm = 0x0100;
        const Summoning = 0x0200;
        const EffectEnabled = 0x0400;
        const SummonTurn = 0x0800;
        const DestroyConfirmed = 0x1000;
        const LeaveConfirmed = 0x2000;
        const BattleDestroyed = 0x4000;
        const CopyingEffect = 0x8000;
        const Chaining = 0x10000;
        const SummonDisabled = 0x20000;
        const ActivateDisabled = 0x40000;
        const EffectReplaced = 0x80000;
        const FlipSummoning = 0x100000;
        const AttackCanceled = 0x200000;
        const Initializing = 0x400000;
        const ToHandWithoutConfirm = 0x800000;
        const JustPos = 0x1000000;
        const ContinuousPos = 0x2000000;
        const Forbidden = 0x4000000;
        const ActFromHand = 0x8000000;
        const OpponentBattle = 0x10000000;
        const FlipSummonTurn = 0x20000000;
        const SpecialSummonTurn = 0x40000000;
        const FlipSummonDisabled = 0x80000000;
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Query: u32 {
        const Code = 0x1;
        const Position = 0x2;
        const Alias = 0x4;
        const Type = 0x8;
        const Level = 0x10;
        const Rank = 0x20;
        const Attribute = 0x40;
        const Race = 0x80;
        const Attack = 0x100;
        const Defense = 0x200;
        const BaseAttack = 0x400;
        const BaseDefense = 0x800;
        const Reason = 0x1000;
        const ReasonCard = 0x2000;
        const EquipCard = 0x4000;
        const TargetCard = 0x8000;
        const OverlayCard = 0x10000;
        const Counters = 0x20000;
        const Owner = 0x40000;
        const Status = 0x80000;
        const LeftScale = 0x200000;
        const RightScale = 0x400000;
        const Link = 0x800000;
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Attribute: u32 {
        const Earth = 0x1;
        const Water = 0x2;
        const Fire = 0x4;
        const Wind = 0x8;
        const Light = 0x10;
        const Dark = 0x20;
        const Devine = 0x40;
        const All = 0x7f;
    }
}

impl Attribute {
    pub const COUNT: u8 = 7;
}


bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Linkmarkers: u32 {
        const BottomLeft = 0x1;
        const Bottom = 0x2;
        const BottomRight = 0x4;
        const Left = 0x8;
        const Right = 0x20;
        const TopLeft = 0x40;
        const Top = 0x80;
        const TopRight = 0x100;
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, PartialOrd, Ord, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum DuelStage {
    Begin = 0,
    Finger = 1,
    Firstgo = 2,
    Dueling = 3,
    Siding = 4,
    End = 5,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum Color {
    Observer = 7,
    Lightblue = 8,
    Red = 11,
    Green = 12,
    Blue = 13,
    Babyblue = 14,
    Pink = 15,
    Yellow = 16,
    White = 17,
    Gray = 18,
    Darkgray = 19,
}

impl std::fmt::Display for Color {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str(match self {
            Color::Observer => "OBSERVER",
            Color::Lightblue => "LIGHTBLUE",
            Color::Red => "RED",
            Color::Green => "GREEN",
            Color::Blue => "BLUE",
            Color::Babyblue => "BABYBLUE",
            Color::Pink => "PINK",
            Color::Yellow => "YELLOW",
            Color::White => "WHITE",
            Color::Gray => "GRAY",
            Color::Darkgray => "DARKGRAY",
        })
    }
}

impl std::str::FromStr for Color {
    type Err = ();

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        Ok(match value.to_ascii_uppercase().as_str() {
            "OBSERVER" => Color::Observer,
            "LIGHTBLUE" => Color::Lightblue,
            "RED" => Color::Red,
            "GREEN" => Color::Green,
            "BLUE" => Color::Blue,
            "BABYBLUE" => Color::Babyblue,
            "PINK" => Color::Pink,
            "YELLOW" => Color::Yellow,
            "WHITE" => Color::White,
            "GRAY" => Color::Gray,
            "DARKGRAY" => Color::Darkgray,
            _ => return Err(()),
        })
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum Hint {
    Event = 1,
    Message = 2,
    SelectMessage = 3,
    OpponentSelected = 4,
    Effect = 5,
    Race = 6,
    Attribute = 7,
    Code = 8,
    Number = 9,
    Card = 10,
    Zone = 11,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u16)]
#[repr(u16)]
pub enum Phase {
    Draw = 0x1,
    Standby = 0x2,
    Main1 = 0x4,
    BattleStart = 0x8,
    BattleStep = 0x10,
    Damage = 0x20,
    DamageCalculate = 0x40,
    Battle = 0x80,
    Main2 = 0x100,
    End = 0x200,
}


bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct SummonType: u32 {
        const Normal = 0x10000000;
        const Advance = 0x11000000;
        const Dual = 0x12000000;
        const Flip = 0x20000000;
        const Special = 0x40000000;
        const Fusion = 0x43000000;
        const Ritual = 0x45000000;
        const Synchro = 0x46000000;
        const Xyz = 0x49000000;
        const Pendulum = 0x4a000000;
        const Link = 0x4c000000;
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum Hand {
    Scissors = 1,
    Rock = 2,
    Paper = 3
}

#[derive(PartialEq, Eq)]
pub enum HandResult {
    Win,
    Draw,
    Lose
}

impl Hand {
    pub fn judge(&self, other: &Self) -> HandResult {
        if self == other { return HandResult::Draw; }
        match self {
            Hand::Scissors => if *other == Hand::Paper { HandResult::Win } else { HandResult::Lose },
            Hand::Rock => if *other == Hand::Scissors { HandResult::Win } else { HandResult::Lose },
            Hand::Paper => if *other == Hand::Rock { HandResult::Win } else { HandResult::Lose },
        }
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Eq, PartialEq, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct OT: u8 {
        const OCG = 1;
        const TCG = 2;
        const Custom = 4;
        const SC = 8;
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr = u8)]
#[repr(u8)]
pub enum Rule {
    OCG = 0,
    TCG = 1,
    SC = 2,
    Custom = 3,
    OCG_TCG = 4,
    All = 5,
}

impl From<Rule> for OT {
    fn from(rule: Rule) -> Self {
        match rule {
            Rule::OCG => OT::OCG,
            Rule::TCG => OT::TCG,
            Rule::SC => OT::SC,
            Rule::Custom => OT::Custom,
            Rule::OCG_TCG => OT::OCG | OT::TCG,
            Rule::All => OT::empty(),
        }
    }
}

impl Rule {
    pub fn check_ot(&self, ot: OT) -> Option<DeckErrorType> {
        let allowed = OT::from(*self);
        if ot.contains(allowed) { return None; }
        if ot.contains(OT::OCG) && allowed != OT::OCG {
            return Some(DeckErrorType::OcgOnly);
        }
        if ot.contains(OT::TCG) && allowed != OT::TCG {
            return Some(DeckErrorType::TcgOnly);
        }
        Some(DeckErrorType::NotAvailable)
    }
}

bitflags! {
    #[repr(transparent)]
    #[derive(BinRead, BinWrite, Clone, Copy, Default, Debug)]
    #[br(map=|x| Self::from_bits_retain(x))]
    #[bw(map=|x: &Self| x.bits())]
    pub struct Category: u32 {
        const Destroy = 0x1;
        const Release = 0x2;
        const Remove = 0x4;
        const ToHand = 0x8;
        const ToDeck = 0x10;
        const ToGrave = 0x20;
        const DeckDestroy = 0x40;
        const HandDestroy = 0x80;
        const Summon = 0x100;
        const SpecialSummon = 0x200;
        const Token = 0x400;
        const GraveAction = 0x800;
        const Position = 0x1000;
        const Control = 0x2000;
        const Disable = 0x4000;
        const DisableSummon = 0x8000;
        const Draw = 0x10000;
        const Search = 0x20000;
        const Equip = 0x40000;
        const Damage = 0x80000;
        const Recover = 0x100000;
        const AttackChange = 0x200000;
        const DefenseChange = 0x400000;
        const Counter = 0x800000;
        const Coin = 0x1000000;
        const Dice = 0x2000000;
        const LeaveGrave = 0x4000000;
        const GraveSpecialSummon = 0x8000000;
        const Negate = 0x10000000;
        const Announce = 0x20000000;
        const FusionSummon = 0x40000000;
        const ToExtra = 0x80000000;
    }
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, FromPrimitive, IntoPrimitive, Debug)]
#[br(map = |v: u32| Operation::from(v))]
#[bw(map = |v: &Operation| u32::from(*v))]
#[repr(u32)]
pub enum Operation {
    Add = 0x40000000,
    Subtract = 0x40000001,
    Multiply = 0x40000002,
    Divide = 0x40000003,
    And = 0x40000004,
    Or  = 0x40000005,
    Negate = 0x40000006,
    Not = 0x40000007,
    IsCode = 0x40000100,
    IsSetcard = 0x40000101,
    IsType = 0x40000102,
    IsRace = 0x40000103,
    IsAttribute = 0x40000104,
    #[num_enum(catch_all)]
    Operand(u32)
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum MasterRule {
    MasterRule1 = 1,
    MasterRule2 = 2,
    MasterRule3 = 3,
    MasterRuleNew = 4,
    MasterRule2020 = 5,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum Activity {
    Summon = 1,
    NormalSummon = 2,
    SpecialSummon = 3,
    FlipSummon = 4,
    Attack = 5,
    BattlePhase = 6,
    Chain = 7,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum CardHint {
    Turn = 1,
    Card = 2,
    Race = 3,
    Attribute = 4,
    Number = 5,
    DescriptionAdd = 6,
    DescriptionRemove = 7,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum PlayerHint {
    DescriptionAdd = 6,
    DescriptionRemove = 7,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=u8)]
#[repr(u8)]
pub enum EffectDescription {
    Operation = 1,
    Reset = 2,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr=i8)]
#[repr(i8)]
pub enum OperationResult {
    Canceled = -1,
    Fail = 0,
    Success = 1,
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, FromPrimitive, IntoPrimitive, Debug)]
#[br(map = |v: u8| WinReason::from(v))]
#[bw(map = |v: &WinReason| u8::from(*v))]
#[repr(u8)]
pub enum WinReason {
    OpponentSurrender = 0,
    LPZero = 1,
    DeckOut = 2,
    Timeout = 3,
    OpponentLeave = 4,
    #[num_enum(catch_all)]
    Other(u8)
}

#[derive(BinRead, BinWrite, Copy, Clone, Eq, PartialEq, TryFromPrimitive, IntoPrimitive, Debug)]
#[brw(repr = i8)]
#[repr(i8)]
pub enum SelectSumMode {
    Exact = 0,
    AtLeast = 1,
}